From e46cca1b8c52ceddb7df3ef1eabedc3cd3228ab7 Mon Sep 17 00:00:00 2001 From: Mark Mennell Date: Wed, 11 Nov 2026 14:43:47 +0800 Subject: [PATCH] FMSG-008 edits: POST /fmsg/:id/edit, edit/edited fields, edit event Implements FMSG-003 v0.5.0. The caller supplies the complete new body; the server derives a copy/insert edit document and sends one edit message for the original and one per add-to batch. Reads present the effective edit: short_text, the data route (original=true for the original) and both thread routes. Edit messages are flagged, routed as an edit event rather than new_msg, and trigger no Web Push. Also FMSG-005 v0.1.1: a reaction to a message sent only to oneself is addressed to the caller instead of being refused. Co-Authored-By: Claude Fable 5.2 --- README.md | 81 ++- cmd/fmsg-webapi/main.go | 1 + internal/edit/edit.go | 155 ++++++ internal/edit/edit_test.go | 132 +++++ internal/handlers/edits.go | 506 ++++++++++++++++++ internal/handlers/edits_integration_test.go | 289 ++++++++++ internal/handlers/edits_test.go | 72 +++ .../handlers/finalization_integration_test.go | 1 + internal/handlers/hub.go | 14 + internal/handlers/messages.go | 40 ++ internal/handlers/push.go | 3 + internal/handlers/reactions.go | 5 +- internal/handlers/thread.go | 52 ++ internal/middleware/oauth.go | 1 + internal/models/models.go | 10 + 15 files changed, 1356 insertions(+), 6 deletions(-) create mode 100644 internal/edit/edit.go create mode 100644 internal/edit/edit_test.go create mode 100644 internal/handlers/edits.go create mode 100644 internal/handlers/edits_integration_test.go create mode 100644 internal/handlers/edits_test.go diff --git a/README.md b/README.md index 7a211ed..348ae61 100644 --- a/README.md +++ b/README.md @@ -360,6 +360,7 @@ the application. | `POST` | `/fmsg/:id/restore` | Take a message or thread out of the trash | | `POST` | `/fmsg/:id/add-to` | Add recipients | | `POST` | `/fmsg/:id/react` | Set or clear an emoji reaction (FMSG-005) | +| `POST` | `/fmsg/:id/edit` | Edit or revert the data of your own sent message (FMSG-008) | | `POST` | `/fmsg/:id/indicate` | Show or clear an indicator, such as composing a reply (FMSG-006) | | `GET` | `/fmsg/:id/data` | Download message data | | `GET` | `/fmsg/:id/thread` | Render direct ancestry as plain text | @@ -563,11 +564,12 @@ event types can be added without breaking clients: | `type` | `data` | Sent when | | ---------- | ------ | --------- | -| `new_msg` | A message object, same shape as an item in the `GET /fmsg` list response (includes `id`). | A new message arrives for the authenticated user. Not sent for reactions. | +| `new_msg` | A message object, same shape as an item in the `GET /fmsg` list response (includes `id`). | A new message arrives for the authenticated user. Not sent for reactions or edits. | | `delivered` | The refreshed message object. | A recipient's delivery state changed on a message the user sent. | | `recipients_added` | The refreshed message object. | An add-to batch was recorded on a message the user participates in. | | `read` | The message object, with `read` and `time_read` set. | The user marked a message read (`POST /fmsg/:id/read`), on this or any other connection, so every tab and device can stop showing it as unread. Sent once, when the message first becomes read. | | `reaction` | The refreshed **subject** message object, with its `reactions` up to date. | A reaction (FMSG-005) on a message the user participates in arrives. The reaction message itself is not pushed as `new_msg` and triggers no Web Push. | +| `edit` | The refreshed **subject** message object, with its `edited` and `short_text` up to date. | An edit (FMSG-008) of a message the user participates in arrives. The edit message itself is not pushed as `new_msg` and triggers no Web Push. | | `indicator` | `{"id": , "root_id": , "from": "
", "emoji": "", "ttl": }`: `from`'s state on message `id` (in the thread starting at `root_id`), valid for `ttl` seconds unless a later one replaces it. An empty `emoji` clears it. | A participant of a message the user is on [shows or clears an indicator](#post-fmsgidindicate) on it, on this host or another. Never stored, and no Web Push. | | `trash` | The message object with its `trash` state, or `{"id": , "trash": "purged"}` for a message deleted for good. | The user moved a message into or out of their [trash](#trash), or deleted it for good, on this or any other connection. | @@ -724,7 +726,9 @@ Retrieves a single message by ID. The authenticated identity must be a participa "reaction": null, "reactions": [ { "emoji": "👍", "from": ["@bob@example.com", "@carol@example.com"] } - ] + ], + "edit": false, + "edited": null } ``` @@ -745,6 +749,23 @@ other message, so clients can hide reaction messages from message lists. latest reaction, grouped by emoji in order of first reaction, with the reactors of each. It is `[]` when there are none. +`edit` and `edited` implement +[FMSG-008 Edits](https://github.com/markmnl/fmsg/blob/main/standards/fmsg-008-edits.md). An edit is an ordinary message: a reply from the +subject's author with `no_reply` and `terminal` set, type +`application/vnd.fmsg.edit`, no attachments, and a body that is empty (revert) +or a well-formed edit document for the subject's data. `edit` is `true` for +such a message and `false` for every other, so clients can hide edit messages +from message lists. `edited` describes the edit in force on this message: +`{"id": , "time": , "size": }` — the latest edit +message and the byte length of the edited data — or `null` when the message +has no edit or its latest one reverts to the original. + +The server applies the effective edit for clients: when `edited` is non-null, +`short_text`, `GET /fmsg/:id/data` and the thread routes present the edited +data, while `type`, `size`, `sha256` and every other field still describe the +original message, which is never altered. `"size": null` means the edit is too +large for this server to apply and the original data is presented. + `add_to` is an array of add-to batches, one per `POST /fmsg/:id/add-to` call. Each batch has a stable `batch_id` (unique within the database and referenced with the message ID), records who added the recipients (`add_to_from`), the @@ -983,7 +1004,8 @@ in `to` or `add_to` — and the message must be sent and not terminal. The reaction is sent immediately as a reaction message: a reply to `:id` with `no_reply` and `terminal` set, type `text/plain;charset=UTF-8`, body the emoji, -addressed to every other participant of the message. Delivery then proceeds +addressed to every other participant of the message, or to the caller alone +for a message they sent only to themselves. Delivery then proceeds exactly as for any sent message, and like any message it counts against the reactor's send limits and each local recipient's receive limits (see [Quotas](#quotas)). A reaction message cannot be replied to, reacted to, or @@ -1008,10 +1030,52 @@ the caller has no reaction returns `200 OK` with `null` values. | `400` | `emoji` is not a single emoji | | `403` | Authenticated identity is not a participant | | `404` | Message not found | -| `409` | Message is a draft, is terminal, has no other participants, or a remote recipient host cannot accept the reaction because it does not hold the message | +| `409` | Message is a draft, is terminal, or a remote recipient host cannot accept the reaction because it does not hold the message | | `413`, `422`, `429` | The reaction would exceed one of the reactor's send limits, as for send | | `503` | fmsgid unavailable, so the send limits can't be checked | +### POST `/fmsg/:id/edit` + +Edits, or reverts an edit of, the data of a message, per +[FMSG-008 Edits](https://github.com/markmnl/fmsg/blob/main/standards/fmsg-008-edits.md). The authenticated identity must be the message's sender +(`from`), and the message must be sent and not terminal. A draft is changed +with `PUT /fmsg/:id` instead. `no_reply` on the message does not prevent +editing it. + +The caller supplies the complete new body; the server derives the edit +document (copy and insert operations against the original data) and sends it +immediately as an edit message: a reply to `:id` with `no_reply` and `terminal` +set and type `application/vnd.fmsg.edit`. One is sent for the original, +addressed to every other participant (or to the caller alone for a message +sent only to themselves), and one for each add-to batch, addressed to the +recipients that batch added. Delivery then proceeds exactly as for any sent +message, and each counts against the sender's send limits and each local +recipient's receive limits (see [Quotas](#quotas)). The original message is +not altered and stays available through `GET /fmsg/:id/data?original=true`. + +**Request body (JSON):** + +| Field | Type | Required | Description | +| ------ | -------- | -------- | ----------- | +| `data` | `string` | no | The complete new UTF-8 body, in the message's existing media type. `null` or absent reverts to the original data. `""` edits the body to empty. | + +An edit that would leave the message's effective data unchanged is idempotent: +nothing is sent and the edit message in force is returned with `200 OK`, or +`null` values when the message has none. + +**Response:** `201 Created` with `{"id": , "time": , "sha256": "<64 hex characters>"}` of the edit message sent for the original. + +**Errors:** + +| Status | Condition | +| ------ | --------- | +| `403` | Authenticated identity is not the message's sender | +| `404` | Message not found | +| `409` | Message is a draft or is terminal, or a remote recipient host cannot accept the edit because it does not hold the message | +| `413` | `data` exceeds the maximum body size, or the edit would exceed one of the sender's send limits | +| `422`, `429` | The edit would exceed one of the sender's send limits, as for send | +| `503` | fmsgid unavailable, so the send limits can't be checked | + ### POST `/fmsg/:id/indicate` Shows or clears the authenticated identity's indicator on a message, per @@ -1053,6 +1117,10 @@ accepted but dropped; clears always go through. Downloads the binary body of a message. The authenticated identity must be a participant — the sender (`from`) or a recipient (listed in `to` or `add_to`). +When the message has an effective [FMSG-008](https://github.com/markmnl/fmsg/blob/main/standards/fmsg-008-edits.md) edit (`edited` is non-null +with a `size`), the edited data is returned. Add `?original=true` for the +original body, which stays available to every participant. + **Response:** The raw message body file with `Content-Disposition: attachment` header. The `Content-Type` is inferred from the stored file extension. **Errors:** @@ -1130,6 +1198,11 @@ truncated. } ``` +A message with an effective [FMSG-008](https://github.com/markmnl/fmsg/blob/main/standards/fmsg-008-edits.md) +edit carries `edited` (as on a message object) and its `body` is the edited +data, with a `cache_key` derived from the edit message's hash rather than the +message's own. + **Errors:** | Status | Condition | diff --git a/cmd/fmsg-webapi/main.go b/cmd/fmsg-webapi/main.go index b63d5d9..c15e113 100644 --- a/cmd/fmsg-webapi/main.go +++ b/cmd/fmsg-webapi/main.go @@ -297,6 +297,7 @@ func registerRoutes(router *gin.Engine, jwtMiddleware gin.HandlerFunc, msgHandle fmsg.POST("/:id/restore", msgHandler.Atomic((*handlers.MessageHandler).Restore)) fmsg.POST("/:id/add-to", msgHandler.Atomic((*handlers.MessageHandler).AddRecipients)) fmsg.POST("/:id/react", msgHandler.Atomic((*handlers.MessageHandler).React)) + fmsg.POST("/:id/edit", msgHandler.Atomic((*handlers.MessageHandler).Edit)) fmsg.POST("/:id/indicate", msgHandler.Indicate) fmsg.GET("/:id/data", msgHandler.DownloadData) fmsg.GET("/:id/thread", msgHandler.ThreadText) diff --git a/internal/edit/edit.go b/internal/edit/edit.go new file mode 100644 index 0000000..8e43966 --- /dev/null +++ b/internal/edit/edit.go @@ -0,0 +1,155 @@ +// Package edit implements the FMSG-008 edit document: a result size followed +// by copy and insert operations that derive a message's edited data from its +// original data. +package edit + +import ( + "encoding/binary" + "errors" +) + +// MediaType is the type of an FMSG-008 edit message. +const MediaType = "application/vnd.fmsg.edit" + +const ( + opCopy = 0 + opInsert = 1 + + sizeLen = 4 // result size + copyLen = 9 // code, offset, length + insertLen = 5 // code, length; literal bytes follow +) + +var ( + // ErrMalformed reports a document that is not a well-formed edit + // document for the subject it was tested against. + ErrMalformed = errors.New("malformed edit document") + // ErrTooLarge reports a well-formed document whose result exceeds the + // caller's limit. + ErrTooLarge = errors.New("edited data exceeds limit") +) + +// Check reports whether doc is a well-formed edit document for subject data +// of subjectLen bytes, returning the byte length of the edited data. +func Check(doc []byte, subjectLen int) (uint32, error) { + return walk(doc, uint64(subjectLen), nil) +} + +// Apply returns the edited data doc produces from subject. limit bounds the +// result size and is checked before anything is allocated; a negative limit +// means no limit. +func Apply(doc, subject []byte, limit int64) ([]byte, error) { + size, err := Check(doc, len(subject)) + if err != nil { + return nil, err + } + if limit >= 0 && int64(size) > limit { + return nil, ErrTooLarge + } + out := make([]byte, 0, size) + if _, err := walk(doc, uint64(len(subject)), func(isCopy bool, a, b uint64) { + if isCopy { + out = append(out, subject[a:a+b]...) + } else { + out = append(out, doc[a:a+b]...) + } + }); err != nil { + return nil, err + } + return out, nil +} + +// walk validates doc, calling emit for each operation: for a copy with the +// subject offset and length, for an insert with the offset of its literal +// bytes within doc and their length. +func walk(doc []byte, subjectLen uint64, emit func(isCopy bool, a, b uint64)) (uint32, error) { + if len(doc) < sizeLen { + return 0, ErrMalformed + } + size := binary.LittleEndian.Uint32(doc) + var total uint64 + for p := sizeLen; p < len(doc); { + switch doc[p] { + case opCopy: + if len(doc)-p < copyLen { + return 0, ErrMalformed + } + off := uint64(binary.LittleEndian.Uint32(doc[p+1:])) + n := uint64(binary.LittleEndian.Uint32(doc[p+5:])) + if n == 0 || off+n > subjectLen { + return 0, ErrMalformed + } + if emit != nil { + emit(true, off, n) + } + total += n + p += copyLen + case opInsert: + if len(doc)-p < insertLen { + return 0, ErrMalformed + } + n := uint64(binary.LittleEndian.Uint32(doc[p+1:])) + if n == 0 || n > uint64(len(doc)-p-insertLen) { + return 0, ErrMalformed + } + if emit != nil { + emit(false, uint64(p+insertLen), n) + } + total += n + p += insertLen + int(n) + default: + return 0, ErrMalformed + } + if total > uint64(size) { + return 0, ErrMalformed + } + } + if total != uint64(size) { + return 0, ErrMalformed + } + return size, nil +} + +// Diff returns a compact edit document producing target from subject. It +// keeps the bytes the two share at the start and at the end and inserts what +// lies between, or inserts the whole target when that is no larger. +func Diff(subject, target []byte) []byte { + prefix := 0 + for prefix < len(subject) && prefix < len(target) && subject[prefix] == target[prefix] { + prefix++ + } + suffix := 0 + for suffix < len(subject)-prefix && suffix < len(target)-prefix && + subject[len(subject)-1-suffix] == target[len(target)-1-suffix] { + suffix++ + } + // A copy costs 9 bytes; one shorter than that is cheaper inserted. + if prefix <= copyLen { + prefix = 0 + } + if suffix <= copyLen { + suffix = 0 + } + middle := target[prefix : len(target)-suffix] + + doc := make([]byte, sizeLen, sizeLen+2*copyLen+insertLen+len(middle)) + binary.LittleEndian.PutUint32(doc, uint32(len(target))) + if prefix > 0 { + doc = appendCopy(doc, 0, prefix) + } + if len(middle) > 0 { + doc = append(doc, opInsert) + doc = binary.LittleEndian.AppendUint32(doc, uint32(len(middle))) + doc = append(doc, middle...) + } + if suffix > 0 { + doc = appendCopy(doc, len(subject)-suffix, suffix) + } + return doc +} + +func appendCopy(doc []byte, offset, length int) []byte { + doc = append(doc, opCopy) + doc = binary.LittleEndian.AppendUint32(doc, uint32(offset)) + return binary.LittleEndian.AppendUint32(doc, uint32(length)) +} diff --git a/internal/edit/edit_test.go b/internal/edit/edit_test.go new file mode 100644 index 0000000..4b53d9b --- /dev/null +++ b/internal/edit/edit_test.go @@ -0,0 +1,132 @@ +package edit + +import ( + "bytes" + "encoding/hex" + "errors" + "strings" + "testing" +) + +// The worked example of FMSG-008. +const ( + specSubject = "I'll see you their at 5pm" + specTarget = "I'll see you there at 5pm" + specDocHex = "19000000" + "000000000010000000" + "01020000007265" + "001200000007000000" +) + +func TestApplySpecExample(t *testing.T) { + doc, _ := hex.DecodeString(specDocHex) + if len(doc) != 29 { + t.Fatalf("doc is %d bytes, want 29", len(doc)) + } + got, err := Apply(doc, []byte(specSubject), -1) + if err != nil { + t.Fatal(err) + } + if string(got) != specTarget { + t.Fatalf("got %q", got) + } +} + +func TestDiffRoundTrip(t *testing.T) { + long := strings.Repeat("The quick brown fox jumps over the lazy dog. ", 40) + cases := []struct{ name, subject, target string }{ + {"spec example", specSubject, specTarget}, + {"identical", long, long}, + {"typo in long text", long, strings.Replace(long, "lazy", "sleepy", 1)}, + {"append", long, long + "And then some."}, + {"prepend", long, "Well. " + long}, + {"truncate", long, long[:100]}, + {"to empty", long, ""}, + {"from empty", "", "hello"}, + {"both empty", "", ""}, + {"unrelated", "abc", "xyz"}, + {"multi-byte", "naïve café — 你好", "naive café — 你好!"}, + {"repeated bytes", strings.Repeat("a", 50), strings.Repeat("a", 30)}, + {"repeated bytes grow", strings.Repeat("a", 30), strings.Repeat("a", 50)}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + doc := Diff([]byte(c.subject), []byte(c.target)) + got, err := Apply(doc, []byte(c.subject), -1) + if err != nil { + t.Fatalf("apply: %v (doc %x)", err, doc) + } + if string(got) != c.target { + t.Fatalf("got %q, want %q", got, c.target) + } + if max := 4 + 5 + len(c.target); len(doc) > max { + t.Fatalf("doc is %d bytes, larger than a full replacement of %d", len(doc), max) + } + }) + } +} + +func TestDiffIsCompact(t *testing.T) { + long := strings.Repeat("x", 100000) + doc := Diff([]byte(long+"teh end"), []byte(long+"the end")) + if len(doc) > 64 { + t.Fatalf("doc is %d bytes for a two-byte change", len(doc)) + } +} + +func TestCheckMalformed(t *testing.T) { + subject := []byte("0123456789") + valid, _ := hex.DecodeString("03000000" + "000200000003000000") + if _, err := Check(valid, len(subject)); err != nil { + t.Fatalf("valid doc rejected: %v", err) + } + cases := map[string]string{ + "empty": "", + "short size": "030000", + "unknown op": "01000000" + "02" + "01000000" + "61", + "truncated copy": "03000000" + "0002000000030000", + "copy past end": "03000000" + "000800000003000000", + "copy offset overflow": "01000000" + "00ffffffff01000000", + "zero-length copy": "00000000" + "000000000000000000", + "zero-length insert": "00000000" + "0100000000", + "insert past end": "05000000" + "0105000000" + "6162", + "sum below result size": "09000000" + "000200000003000000", + "sum above result size": "01000000" + "000200000003000000", + "result size without ops": "01000000", + "trailing byte": "03000000" + "000200000003000000" + "00", + "truncated insert header": "01000000" + "010100", + "insert length wraps": "01000000" + "01ffffffff" + "61", + } + for name, h := range cases { + doc, err := hex.DecodeString(h) + if err != nil { + t.Fatalf("%s: bad hex", name) + } + if _, err := Check(doc, len(subject)); !errors.Is(err, ErrMalformed) { + t.Errorf("%s: got %v, want ErrMalformed", name, err) + } + if _, err := Apply(doc, subject, -1); !errors.Is(err, ErrMalformed) { + t.Errorf("%s: apply got %v, want ErrMalformed", name, err) + } + } +} + +func TestEmptyResult(t *testing.T) { + got, err := Apply([]byte{0, 0, 0, 0}, []byte("anything"), -1) + if err != nil || len(got) != 0 { + t.Fatalf("got %q, %v", got, err) + } +} + +func TestApplyLimit(t *testing.T) { + subject := bytes.Repeat([]byte("a"), 1000) + // Twenty copies of the whole subject: 184 bytes describing 20000. + doc := []byte{0x20, 0x4e, 0, 0} + for i := 0; i < 20; i++ { + doc = appendCopy(doc, 0, 1000) + } + if _, err := Apply(doc, subject, 5000); !errors.Is(err, ErrTooLarge) { + t.Fatalf("got %v, want ErrTooLarge", err) + } + got, err := Apply(doc, subject, 20000) + if err != nil || len(got) != 20000 { + t.Fatalf("got %d bytes, %v", len(got), err) + } +} diff --git a/internal/handlers/edits.go b/internal/handlers/edits.go new file mode 100644 index 0000000..d8a8410 --- /dev/null +++ b/internal/handlers/edits.go @@ -0,0 +1,506 @@ +package handlers + +import ( + "bytes" + "context" + "encoding/hex" + "errors" + "log" + "net/http" + "os" + "sort" + "strings" + "time" + "unicode/utf8" + + "github.com/gin-gonic/gin" + "github.com/jackc/pgx/v5" + "github.com/markmnl/fmsg-webapi/internal/edit" + "github.com/markmnl/fmsg-webapi/internal/middleware" + "github.com/markmnl/fmsg-webapi/internal/models" + "github.com/markmnl/fmsgd/pkg/message" +) + +// FMSG-008 Edits. An edit is an ordinary message: a reply (pid set) from the +// subject's author with no reply and terminal set, not important, with no +// add-to batch and no attachments, of type application/vnd.fmsg.edit, whose +// data is empty (revert) or a well-formed edit document for the subject's +// data. A subject's effective edit is its latest edit message by time, ties +// broken by the greater message hash. The server applies it for clients: +// short_text and the data route present the edited data. + +// isEditMediaType reports whether a stored type string is the edit media type. +func isEditMediaType(mediaType string) bool { + return strings.EqualFold(strings.TrimSpace(mediaType), edit.MediaType) +} + +// editShape reports whether a message's metadata has the shape of an edit, +// before its author and data are examined. +func editShape(hasPid, noReply, terminal, important, hasAddTo bool, mediaType string, attachments int) bool { + return hasPid && noReply && terminal && !important && !hasAddTo && + 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) { + if dataPath == "" { + return nil, true + } + cleanPath, ok := safeDataPath(dataPath, h.DataDir) + if !ok { + return nil, false + } + 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 data, true +} + +// editLimit bounds the size of edited data this server will produce for a +// subject (FMSG-008 Applying Edits). +func (h *MessageHandler) editLimit(subjectLen int) int64 { + return h.MaxDataSize + int64(subjectLen) +} + +// 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) { + var pid int64 + var size int + var dataPath, subjectPath string + err := h.q().QueryRow(ctx, ` + SELECT r.pid, r.size, r.filepath, s.filepath + FROM msg r JOIN msg s ON s.id = r.pid + 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) + } + return 0, false + } + if size == 0 { + return pid, true + } + subject, ok := h.readBody(subjectPath) + if !ok { + return 0, false + } + doc, ok := h.readBody(dataPath) + if !ok { + return 0, false + } + if _, err := edit.Check(doc, len(subject)); err != nil { + return 0, false + } + return pid, true +} + +// editRowFilter selects sent messages r having the shape of an edit of their +// parent s, written by s's author. $2 is the edit media type. +const editRowFilter = `r.time_sent IS NOT NULL + AND r.is_terminal AND r.no_reply AND NOT r.is_important + AND lower(btrim(r.type)) = $2 + AND lower(r.from_addr) = lower(s.from_addr) + AND NOT EXISTS (SELECT 1 FROM msg_attachment a WHERE a.msg_id = r.id) + AND NOT EXISTS (SELECT 1 FROM msg_add_to_batch b WHERE b.msg_id = r.id)` + +// editRow is one stored edit-shaped message on a subject. +type editRow struct { + msgID int64 + time float64 + hash []byte // message hash; nil until the host has computed it + size int + dataPath string +} + +// effectiveEdit is the edit in force on a subject. +type effectiveEdit struct { + msgID int64 + time float64 + hash []byte + revert bool // the latest edit reverts to the original + applied bool // data holds the edited data + data []byte // edited data, when applied +} + +// edited returns the API representation, or nil when the subject presents its +// original data because the latest edit reverts. +func (e *effectiveEdit) edited() *models.Edited { + if e == nil || e.revert { + return nil + } + out := &models.Edited{ID: e.msgID, Time: e.time} + if e.applied { + n := len(e.data) + out.Size = &n + } + return out +} + +// 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 { + if len(subjectIDs) == 0 { + return nil + } + rows, err := h.q().Query(ctx, ` + SELECT r.pid, r.id, r.time_sent, r.sha256, r.size, r.filepath, s.filepath + FROM msg r JOIN msg s ON s.id = r.pid + WHERE r.pid = ANY($1) AND `+editRowFilter, + subjectIDs, edit.MediaType, + ) + if err != nil { + log.Printf("load edits: %v", err) + return nil + } + bySubject := make(map[int64][]editRow) + subjectPaths := make(map[int64]string) + for rows.Next() { + var subjectID int64 + var r editRow + 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 + } + 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 + } + + result := make(map[int64]*effectiveEdit, len(bySubject)) + for subjectID, candidates := range bySubject { + // Newest first: the first that is an edit message is the effective one. + sort.Slice(candidates, func(i, j int) bool { + a, b := candidates[i], candidates[j] + if a.time != b.time { + return a.time > b.time + } + return bytes.Compare(a.hash, b.hash) > 0 + }) + var subject []byte + subjectRead := false + for _, r := range candidates { + eff := &effectiveEdit{msgID: r.msgID, time: r.time, hash: r.hash} + if r.size == 0 { + eff.revert = true + result[subjectID] = eff + break + } + if !subjectRead { + var ok bool + if subject, ok = h.readBody(subjectPaths[subjectID]); !ok { + break + } + subjectRead = true + } + doc, ok := h.readBody(r.dataPath) + if !ok { + continue + } + data, err := edit.Apply(doc, subject, h.editLimit(len(subject))) + if errors.Is(err, edit.ErrMalformed) { + continue + } + if err == nil { + eff.applied = true + eff.data = data + } + // A well-formed edit too large to apply stays the effective + // edit: the original data is presented. + result[subjectID] = eff + break + } + } + return result +} + +// shortTextOf returns the short_text preview of in-memory body data, as +// extractShortText does for a stored body. +func (h *MessageHandler) shortTextOf(data []byte, mimeType string) string { + if h.ShortTextSize <= 0 || !isTextMIME(mimeType) { + return "" + } + if len(data) > h.ShortTextSize { + data = data[:h.ShortTextSize] + } + for len(data) > 0 && !utf8.Valid(data) { + data = data[:len(data)-1] + } + 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) { + ids := make([]int64, len(items)) + for i := range items { + ids[i] = items[i].ID + } + edits := h.loadEffectiveEdits(ctx, ids) + for i := range items { + it := &items[i] + if editShape(it.HasPid, it.NoReply, it.Terminal, it.Important, it.HasAddTo, it.Type, len(it.Attachments)) { + _, it.Edit = h.editSubject(ctx, it.ID) + } + if eff := edits[it.ID]; eff != nil { + it.Edited = eff.edited() + if eff.applied { + it.ShortText = h.shortTextOf(eff.data, it.Type) + } + } + } +} + +// without returns addrs less addr, deduplicated case-insensitively, in order. +func without(addrs []string, addr string) []string { + seen := map[string]bool{strings.ToLower(addr): true} + var out []string + for _, a := range addrs { + key := strings.ToLower(a) + if seen[key] { + continue + } + seen[key] = true + out = append(out, a) + } + return out +} + +// editTarget is one edit message to send: the branch it replies to and its +// recipients. +type editTarget struct { + parentHash *string + to []string +} + +// editTargets returns the edit messages needed for every reader of subject to +// observe an edit (FMSG-008 Recipients and Add-to Batches): one for the +// original, to its participants other than the editor or to the editor alone +// when there is none, and one for each add-to batch, to the recipients that +// batch added. +func editTargets(subject *models.Message, editor string) []editTarget { + to := without(subject.To, editor) + if len(to) == 0 { + to = []string{editor} + } + targets := []editTarget{{parentHash: subject.SHA256, to: to}} + for _, b := range subject.AddTo { + if added := without(b.To, editor); len(added) > 0 && b.SHA256 != nil { + targets = append(targets, editTarget{parentHash: b.SHA256, to: added}) + } + } + return targets +} + +// editInput is the request body of POST /fmsg/:id/edit. +type editInput struct { + Data *string `json:"data"` // the complete new body; null reverts to the original +} + +// existingEditResponse is the 200 body naming the edit message already in +// force, or nulls when the subject has none. +func existingEditResponse(eff *effectiveEdit) gin.H { + if eff == nil { + return gin.H{"id": nil, "time": nil, "sha256": nil} + } + return gin.H{"id": eff.msgID, "time": eff.time, "sha256": hex.EncodeToString(eff.hash)} +} + +// Edit handles POST /fmsg/:id/edit — edits, or reverts an edit of, the data of +// the caller's own sent message by sending FMSG-008 edit messages. The caller +// supplies the complete new body; the edit document is derived here. An edit +// that leaves the effective data unchanged is idempotent and sends nothing. +func (h *MessageHandler) Edit(c *gin.Context) { + identity := middleware.GetIdentity(c) + msgID, ok := resolveID(c, h.q()) + if !ok { + return + } + + var in editInput + if err := c.ShouldBindJSON(&in); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) + return + } + if in.Data != nil && int64(len(*in.Data)) > h.MaxDataSize { + c.JSON(http.StatusRequestEntityTooLarge, gin.H{"error": "message data exceeds maximum size"}) + return + } + + ctx := c.Request.Context() + subject, subjectPath, err := h.fetchMessage(ctx, msgID) + if err != nil { + if errors.Is(err, pgx.ErrNoRows) { + c.JSON(http.StatusNotFound, gin.H{"error": "message not found"}) + } else { + log.Printf("edit %d: fetch: %v", msgID, err) + c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to retrieve message"}) + } + return + } + if draftHidden([]string{identity}, subject.From, subject.Time) || purgedFor(ctx, h.q(), identity, msgID) { + c.JSON(http.StatusNotFound, gin.H{"error": "message not found"}) + return + } + if !sameAddr(subject.From, identity) { + if !isRecipient(subject.To, identity) && !addToContains(subject.AddTo, identity) { + c.JSON(http.StatusForbidden, gin.H{"error": "access denied"}) + return + } + c.JSON(http.StatusForbidden, gin.H{"error": "only the author may edit a message"}) + return + } + if subject.Time == nil { + c.JSON(http.StatusConflict, gin.H{"error": "a draft is changed with PUT, not edited"}) + return + } + if subject.Terminal { + c.JSON(http.StatusConflict, gin.H{"error": "message is terminal; it cannot be edited"}) + return + } + if subject.SHA256 == nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": "message has no finalized identity"}) + return + } + + original, ok := h.readBody(subjectPath) + if !ok { + c.JSON(http.StatusNotFound, gin.H{"error": "message data not available"}) + return + } + current := h.loadEffectiveEdits(ctx, []int64{msgID})[msgID] + + // Idempotency: nothing is sent when the effective data would not change. + var doc []byte + if in.Data == nil { + if current == nil || current.revert { + c.JSON(http.StatusOK, existingEditResponse(current)) + return + } + } else { + want := []byte(*in.Data) + unchanged := bytes.Equal(original, want) + if current != nil && !current.revert { + unchanged = current.applied && bytes.Equal(current.data, want) + } + if unchanged { + c.JSON(http.StatusOK, existingEditResponse(current)) + return + } + doc = edit.Diff(original, want) + } + + targets := editTargets(subject, identity) + + // As for any reply, refuse when a remote recipient host can never accept + // it because it does not hold the subject (SPEC §10.3, code 6). + var all []string + for _, t := range targets { + all = append(all, t.to...) + } + if replyDomains := remoteRecipientDomains(&models.Message{To: all}, h.LocalDomain); len(replyDomains) > 0 { + parentFromDomain, byDomain, derr := h.parentDeliveryByDomain(ctx, msgID) + if derr != nil { + log.Printf("edit %d: verify delivery: %v", msgID, derr) + c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to verify parent delivery"}) + return + } + if blocked := undeliverableReplyDomains(replyDomains, parentFromDomain, byDomain); len(blocked) > 0 { + c.JSON(http.StatusConflict, gin.H{"error": "edit cannot be accepted by recipient host(s): " + strings.Join(blocked, "; ")}) + return + } + } + + // An edit is a message like any other: each one sent counts against the + // sender's send limits, and its recipients' receive limits. + size := int64(len(doc)) + if !h.checkSendQuota(c, identity, size*int64(len(targets))) { + return + } + now := float64(time.Now().UnixMicro()) / 1e6 + tx, err := h.q().Begin(ctx) + 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) + + var files message.Files + onRollback(c, func() { files.Cleanup() }) + editIDs := make([]int64, len(targets)) + var firstHash []byte + for i, t := range targets { + var editID int64 + if err := tx.QueryRow(ctx, + `INSERT INTO msg (version, pid, psha256, no_reply, is_important, is_deflate, is_terminal, from_addr, topic, type, size, filepath, time_sent) + VALUES (1, $1, decode($5,'hex'), true, false, false, true, $2, '', $3, $4, '', NULL) + RETURNING id`, + msgID, identity, edit.MediaType, len(doc), t.parentHash, + ).Scan(&editID); err != nil { + log.Printf("edit %d: insert: %v", msgID, err) + c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to send edit"}) + return + } + dataPath, err := h.saveMessageData(identity, editID, ".bin", string(doc)) + if err != nil { + log.Printf("edit %d: save data: %v", msgID, err) + c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to save edit"}) + return + } + createdFile(c, dataPath) + if _, err := tx.Exec(ctx, "UPDATE msg SET filepath = $1 WHERE id = $2", dataPath, editID); err != nil { + log.Printf("edit %d: update filepath: %v", msgID, err) + 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) + c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to send edit"}) + return + } + } + hash, err := message.Finalize(ctx, finalizationTx{tx}, editID, now, &files) + if err != nil { + log.Printf("finalize edit: %v", err) + c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to finalize edit"}) + return + } + editIDs[i] = editID + if i == 0 { + firstHash = hash + } + } + if err := tx.Commit(ctx); err != nil { + log.Printf("edit %d: commit: %v", msgID, err) + c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to send edit"}) + return + } + + // fmsgd's outbound sender skips the local domain, so local recipients + // have their delivery resolved here, as Send does. + afterCommit(c, func() { + 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) + } + }) + + c.JSON(http.StatusCreated, gin.H{"id": editIDs[0], "time": now, "sha256": hex.EncodeToString(firstHash)}) +} diff --git a/internal/handlers/edits_integration_test.go b/internal/handlers/edits_integration_test.go new file mode 100644 index 0000000..a1d90cd --- /dev/null +++ b/internal/handlers/edits_integration_test.go @@ -0,0 +1,289 @@ +package handlers + +import ( + "context" + "fmt" + "strings" + "testing" + + "github.com/markmnl/fmsg-webapi/internal/edit" +) + +const ( + editAlice = "@alice@example.com" + editBob = "@bob@example.com" + editCarol = "@carol@example.com" +) + +// sendTo creates and sends a plain-text message from alice, returning its id. +func (a *finalizationAPI) sendTo(t *testing.T, to []string, body string, extra map[string]any) string { + t.Helper() + in := map[string]any{"version": 1, "from": editAlice, "to": to, "topic": "edits", "type": "text/plain;charset=UTF-8", "data": body} + for k, v := range extra { + in[k] = v + } + id := fmt.Sprintf("%.0f", jsonResponse(t, a.request(editAlice, "POST", "/fmsg", in), 201)["id"]) + jsonResponse(t, a.request(editAlice, "POST", "/fmsg/"+id+"/send", nil), 200) + return id +} + +func (a *finalizationAPI) body(t *testing.T, identity, path string) string { + t.Helper() + w := a.request(identity, "GET", path, nil) + if w.Code != 200 { + t.Fatalf("GET %s as %s: HTTP %d: %s", path, identity, w.Code, w.Body) + } + return w.Body.String() +} + +func TestEditLifecycle(t *testing.T) { + a := newFinalizationAPI(t) + const original, fixed = "I'll see you their at 5pm", "I'll see you there at 5pm" + id := a.sendTo(t, []string{editBob}, original, nil) + + // Only the author edits. + for _, who := range []string{editBob, "@outsider@example.com"} { + if w := a.request(who, "POST", "/fmsg/"+id+"/edit", map[string]any{"data": "hijacked"}); w.Code != 403 { + t.Fatalf("%s edit: HTTP %d, want 403: %s", who, w.Code, w.Body) + } + } + // Nothing to do: no edit in force and the data is unchanged, or a revert. + for _, in := range []map[string]any{{"data": original}, {"data": nil}, {}} { + if v := jsonResponse(t, a.request(editAlice, "POST", "/fmsg/"+id+"/edit", in), 200); v["id"] != nil || v["sha256"] != nil { + t.Fatalf("no-op edit %v returned %v", in, v) + } + } + + first := jsonResponse(t, a.request(editAlice, "POST", "/fmsg/"+id+"/edit", map[string]any{"data": fixed}), 201) + if len(first["sha256"].(string)) != 64 { + t.Fatalf("edit response %v", first) + } + editID := fmt.Sprintf("%.0f", first["id"]) + + // The stored edit message is a compact, well-formed edit document. + var typ, path string + var noReply, terminal bool + if err := a.pool.QueryRow(context.Background(), `SELECT type, filepath, no_reply, is_terminal FROM msg WHERE id=$1`, editID).Scan(&typ, &path, &noReply, &terminal); err != nil { + t.Fatal(err) + } + doc, ok := a.h.readBody(path) + if !ok || typ != edit.MediaType || !noReply || !terminal { + t.Fatalf("stored edit: type %q no_reply %v terminal %v read %v", typ, noReply, terminal, ok) + } + if got, err := edit.Apply(doc, []byte(original), -1); err != nil || string(got) != fixed { + t.Fatalf("stored edit document applies to %q, %v", got, err) + } + if len(doc) >= 4+5+len(fixed) { + t.Fatalf("edit document is %d bytes, no smaller than a full replacement", len(doc)) + } + + // Every participant sees the edited data; the original stays available. + for _, who := range []string{editAlice, editBob} { + msg := jsonResponse(t, a.request(who, "GET", "/fmsg/"+id, nil), 200) + edited, _ := msg["edited"].(map[string]any) + if edited == nil || edited["id"] != first["id"] || edited["size"] != float64(len(fixed)) { + t.Fatalf("%s: edited = %v", who, msg["edited"]) + } + if msg["short_text"] != fixed || msg["edit"] != false || msg["size"] != float64(len(original)) { + t.Fatalf("%s: short_text %v edit %v size %v", who, msg["short_text"], msg["edit"], msg["size"]) + } + if got := a.body(t, who, "/fmsg/"+id+"/data"); got != fixed { + t.Fatalf("%s data = %q", who, got) + } + if got := a.body(t, who, "/fmsg/"+id+"/data?original=true"); got != original { + t.Fatalf("%s original data = %q", who, got) + } + if got := a.body(t, who, "/fmsg/"+id+"/thread"); !strings.Contains(got, fixed) || strings.Contains(got, original) { + t.Fatalf("%s thread = %q", who, got) + } + thread := a.body(t, who, "/fmsg/"+id+"/thread/messages") + if !strings.Contains(thread, fixed) || strings.Contains(thread, original) || !strings.Contains(thread, `"edited"`) { + t.Fatalf("%s thread messages = %s", who, thread) + } + } + if w := a.request("@outsider@example.com", "GET", "/fmsg/"+id+"/data", nil); w.Code != 403 { + t.Fatalf("outsider data: HTTP %d", w.Code) + } + + // The edit message itself is flagged so clients hide it, and is listed + // for its recipient alongside the edited subject. + if msg := jsonResponse(t, a.request(editBob, "GET", "/fmsg/"+editID, nil), 200); msg["edit"] != true || msg["edited"] != nil { + t.Fatalf("edit message: edit %v edited %v", msg["edit"], msg["edited"]) + } + list := a.body(t, editBob, "/fmsg") + if !strings.Contains(list, `"edit":true`) || !strings.Contains(list, `"short_text":"`+fixed+`"`) { + t.Fatalf("bob list = %s", list) + } + + // Repeating the edit sends nothing. + if again := jsonResponse(t, a.request(editAlice, "POST", "/fmsg/"+id+"/edit", map[string]any{"data": fixed}), 200); again["id"] != first["id"] { + t.Fatalf("repeat edit returned %v", again) + } + + // A second edit is a delta against the original and supersedes the first. + const second = "See you there at 6pm" + jsonResponse(t, a.request(editAlice, "POST", "/fmsg/"+id+"/edit", map[string]any{"data": second}), 201) + if got := a.body(t, editBob, "/fmsg/"+id+"/data"); got != second { + t.Fatalf("data after second edit = %q", got) + } + + // Editing to empty is an edit, not a revert. + jsonResponse(t, a.request(editAlice, "POST", "/fmsg/"+id+"/edit", map[string]any{"data": ""}), 201) + if msg := jsonResponse(t, a.request(editBob, "GET", "/fmsg/"+id, nil), 200); msg["edited"].(map[string]any)["size"] != float64(0) { + t.Fatalf("edited to empty = %v", msg["edited"]) + } + if got := a.body(t, editBob, "/fmsg/"+id+"/data"); got != "" { + t.Fatalf("data after emptying = %q", got) + } + + // Revert restores the original; reverting again sends nothing. + revert := jsonResponse(t, a.request(editAlice, "POST", "/fmsg/"+id+"/edit", map[string]any{"data": nil}), 201) + msg := jsonResponse(t, a.request(editBob, "GET", "/fmsg/"+id, nil), 200) + if msg["edited"] != nil || msg["short_text"] != original { + t.Fatalf("after revert: edited %v short_text %v", msg["edited"], msg["short_text"]) + } + if got := a.body(t, editBob, "/fmsg/"+id+"/data"); got != original { + t.Fatalf("data after revert = %q", got) + } + if again := jsonResponse(t, a.request(editAlice, "POST", "/fmsg/"+id+"/edit", map[string]any{}), 200); again["id"] != revert["id"] { + t.Fatalf("repeat revert returned %v", again) + } + // Editing back to the original text after a revert also changes nothing. + jsonResponse(t, a.request(editAlice, "POST", "/fmsg/"+id+"/edit", map[string]any{"data": original}), 200) +} + +func TestEditRefusals(t *testing.T) { + a := newFinalizationAPI(t) + + draft := a.draft(t, editAlice, "draft", nil) + if w := a.request(editAlice, "POST", "/fmsg/"+draft+"/edit", map[string]any{"data": "x"}); w.Code != 409 { + t.Errorf("edit a draft: HTTP %d, want 409: %s", w.Code, w.Body) + } + if w := a.request(editBob, "POST", "/fmsg/"+draft+"/edit", map[string]any{"data": "x"}); w.Code != 404 { + t.Errorf("edit another's draft: HTTP %d, want 404: %s", w.Code, w.Body) + } + + terminal := a.sendTo(t, []string{editBob}, "final word", map[string]any{"terminal": true}) + if w := a.request(editAlice, "POST", "/fmsg/"+terminal+"/edit", map[string]any{"data": "x"}); w.Code != 409 { + t.Errorf("edit a terminal message: HTTP %d, want 409: %s", w.Code, w.Body) + } + + // An edit message is terminal, so it cannot itself be edited. + id := a.sendTo(t, []string{editBob}, "hello", nil) + e := jsonResponse(t, a.request(editAlice, "POST", "/fmsg/"+id+"/edit", map[string]any{"data": "hello!"}), 201) + if w := a.request(editAlice, "POST", fmt.Sprintf("/fmsg/%.0f/edit", e["id"]), map[string]any{"data": "x"}); w.Code != 409 { + t.Errorf("edit an edit: HTTP %d, want 409: %s", w.Code, w.Body) + } + + if w := a.request(editAlice, "POST", "/fmsg/"+id+"/edit", map[string]any{"data": strings.Repeat("x", 1<<20+1)}); w.Code != 413 { + t.Errorf("oversized edit: HTTP %d, want 413", w.Code) + } + if w := a.request(editAlice, "POST", "/fmsg/999999/edit", map[string]any{"data": "x"}); w.Code != 404 { + t.Errorf("edit a missing message: HTTP %d, want 404", w.Code) + } + + // A no-reply message is still its author's to edit. + quiet := a.sendTo(t, []string{editBob}, "fyi", map[string]any{"no_reply": true}) + jsonResponse(t, a.request(editAlice, "POST", "/fmsg/"+quiet+"/edit", map[string]any{"data": "FYI"}), 201) +} + +// An edit-shaped message from someone other than the subject's author, or +// with a malformed edit document, is an ordinary message. +func TestEditIgnoresForgedAndMalformed(t *testing.T) { + a := newFinalizationAPI(t) + ctx := context.Background() + id := a.sendTo(t, []string{editBob}, "the original", nil) + good := jsonResponse(t, a.request(editAlice, "POST", "/fmsg/"+id+"/edit", map[string]any{"data": "the edit"}), 201) + + insert := func(from string, doc []byte, when float64) int64 { + t.Helper() + var rid int64 + if err := a.pool.QueryRow(ctx, + `INSERT INTO msg (version, pid, no_reply, is_important, is_deflate, is_terminal, from_addr, topic, type, size, filepath, time_sent) + VALUES (1, $1, true, false, false, true, $2, '', $3, $4, '', NULL) + RETURNING id`, id, from, edit.MediaType, len(doc), + ).Scan(&rid); err != nil { + t.Fatal(err) + } + path, err := a.h.saveMessageData(from, rid, ".bin", string(doc)) + if err != nil { + t.Fatal(err) + } + // Stamped as sent the way a received message is, without finalizing. + if _, err := a.pool.Exec(ctx, + `UPDATE msg SET filepath=$1, time_sent=$2, sha256=sha256($3::bytea), wire_header='\x00', wire_message='{}' WHERE id=$4`, + path, when, fmt.Sprintf("forged %s %f", from, when), rid); err != nil { + t.Fatal(err) + } + return rid + } + later := good["time"].(float64) + 60 + forged := insert(editBob, edit.Diff([]byte("the original"), []byte("bob was here")), later) + malformed := insert(editAlice, []byte{9, 0, 0, 0, 0, 0xff, 0, 0, 0, 1, 0, 0, 0}, later+1) + + msg := jsonResponse(t, a.request(editBob, "GET", "/fmsg/"+id, nil), 200) + if msg["edited"].(map[string]any)["id"] != good["id"] { + t.Fatalf("effective edit = %v, want %v", msg["edited"], good["id"]) + } + if got := a.body(t, editBob, "/fmsg/"+id+"/data"); got != "the edit" { + t.Fatalf("data = %q", got) + } + for _, rid := range []int64{forged, malformed} { + if _, ok := a.h.editSubject(ctx, rid); ok { + t.Errorf("message %d recognised as an edit", rid) + } + } +} + +func TestEditReachesAddedRecipients(t *testing.T) { + a := newFinalizationAPI(t) + id := a.sendTo(t, []string{editBob}, "meet at noon", nil) + batch := jsonResponse(t, a.request(editBob, "POST", "/fmsg/"+id+"/add-to", map[string]any{"add_to": []string{editCarol}}), 200) + jsonResponse(t, a.request(editAlice, "POST", "/fmsg/"+id+"/edit", map[string]any{"data": "meet at one"}), 201) + + // One edit message per branch: the original's to bob, the batch's to carol. + rows, err := a.pool.Query(context.Background(), + `SELECT encode(m.psha256,'hex'), (SELECT string_agg(addr, ',') FROM msg_to t WHERE t.msg_id = m.id) + FROM msg m WHERE m.pid = $1 AND m.type = $2 ORDER BY m.id`, id, edit.MediaType) + if err != nil { + t.Fatal(err) + } + defer rows.Close() + got := map[string]string{} + for rows.Next() { + var parent, to string + if err := rows.Scan(&parent, &to); err != nil { + t.Fatal(err) + } + got[parent] = to + } + subject := jsonResponse(t, a.request(editAlice, "GET", "/fmsg/"+id, nil), 200) + want := map[string]string{subject["sha256"].(string): editBob, batch["sha256"].(string): editCarol} + if fmt.Sprint(got) != fmt.Sprint(want) { + t.Fatalf("edit messages = %v, want %v", got, want) + } + + for _, who := range []string{editBob, editCarol} { + if got := a.body(t, who, "/fmsg/"+id+"/data"); got != "meet at one" { + t.Fatalf("%s data = %q", who, got) + } + } +} + +// A message sent only to oneself can be edited and reacted to: the edit and +// the reaction are addressed to the sender (FMSG-008, FMSG-005 v0.1.1). +func TestEditAndReactNoteToSelf(t *testing.T) { + a := newFinalizationAPI(t) + id := a.sendTo(t, []string{editAlice}, "remember teh milk", nil) + + jsonResponse(t, a.request(editAlice, "POST", "/fmsg/"+id+"/edit", map[string]any{"data": "remember the milk"}), 201) + if got := a.body(t, editAlice, "/fmsg/"+id+"/data"); got != "remember the milk" { + t.Fatalf("data = %q", got) + } + + jsonResponse(t, a.request(editAlice, "POST", "/fmsg/"+id+"/react", map[string]any{"emoji": "👍"}), 201) + msg := jsonResponse(t, a.request(editAlice, "GET", "/fmsg/"+id, nil), 200) + if reactions, _ := msg["reactions"].([]any); len(reactions) != 1 { + t.Fatalf("reactions = %v", msg["reactions"]) + } +} diff --git a/internal/handlers/edits_test.go b/internal/handlers/edits_test.go new file mode 100644 index 0000000..270e892 --- /dev/null +++ b/internal/handlers/edits_test.go @@ -0,0 +1,72 @@ +package handlers + +import ( + "reflect" + "testing" + + "github.com/markmnl/fmsg-webapi/internal/edit" + "github.com/markmnl/fmsg-webapi/internal/models" +) + +func TestEditShape(t *testing.T) { + if !editShape(true, true, true, false, false, edit.MediaType, 0) { + t.Error("canonical edit shape rejected") + } + if !editShape(true, true, true, false, false, "Application/VND.fmsg.Edit", 0) { + t.Error("type is not matched case-insensitively") + } + cases := map[string]bool{ + "no pid": editShape(false, true, true, false, false, edit.MediaType, 0), + "no no-reply": editShape(true, false, true, false, false, edit.MediaType, 0), + "not terminal": editShape(true, true, false, false, false, edit.MediaType, 0), + "important": editShape(true, true, true, true, false, edit.MediaType, 0), + "add-to": editShape(true, true, true, false, true, edit.MediaType, 0), + "wrong type": editShape(true, true, true, false, false, "application/octet-stream", 0), + "parameter": editShape(true, true, true, false, false, edit.MediaType+";v=1", 0), + "attachment": editShape(true, true, true, false, false, edit.MediaType, 1), + } + for name, got := range cases { + if got { + t.Errorf("%s: shape accepted", name) + } + } +} + +func TestEditTargets(t *testing.T) { + alice, bob, carol, dave := "@alice@example.com", "@bob@example.com", "@carol@example.com", "@dave@example.com" + orig, b1, b2 := "aa", "bb", "cc" + + // The original goes to its other participants; each batch to those it added. + got := editTargets(&models.Message{ + From: alice, To: []string{bob, "@ALICE@example.com", bob}, SHA256: &orig, + AddTo: []models.AddToBatch{ + {SHA256: &b1, AddToFrom: bob, To: []string{carol, bob}}, + {SHA256: &b2, AddToFrom: alice, To: []string{alice}}, // re-serves only the editor + {SHA256: &b2, AddToFrom: carol, To: []string{dave}}, + }, + }, alice) + want := []editTarget{ + {parentHash: &orig, to: []string{bob}}, + {parentHash: &b1, to: []string{carol, bob}}, + {parentHash: &b2, to: []string{dave}}, + } + if !reflect.DeepEqual(got, want) { + t.Errorf("targets = %+v, want %+v", got, want) + } + + // A message sent only to oneself is edited by a message to oneself. + self := editTargets(&models.Message{From: alice, To: []string{alice}, SHA256: &orig}, alice) + if len(self) != 1 || !reflect.DeepEqual(self[0].to, []string{alice}) { + t.Errorf("note to self targets = %+v", self) + } +} + +func TestShortTextOf(t *testing.T) { + h := &MessageHandler{ShortTextSize: 5} + if got := h.shortTextOf([]byte("héllo world"), "text/plain;charset=UTF-8"); got != "héll" { + t.Errorf("got %q", got) + } + if got := h.shortTextOf([]byte("abc"), "application/json"); got != "" { + t.Errorf("non-text previewed: %q", got) + } +} diff --git a/internal/handlers/finalization_integration_test.go b/internal/handlers/finalization_integration_test.go index 2e64e44..48f01ba 100644 --- a/internal/handlers/finalization_integration_test.go +++ b/internal/handlers/finalization_integration_test.go @@ -103,6 +103,7 @@ func newFinalizationAPIWithID(t *testing.T, fmsgID http.Handler) *finalizationAP r.POST("/fmsg/:id/restore", h.Atomic((*MessageHandler).Restore)) r.POST("/fmsg/:id/add-to", h.Atomic((*MessageHandler).AddRecipients)) r.POST("/fmsg/:id/react", h.Atomic((*MessageHandler).React)) + r.POST("/fmsg/:id/edit", h.Atomic((*MessageHandler).Edit)) r.POST("/fmsg/:id/indicate", h.Indicate) r.GET("/fmsg/:id/thread", h.ThreadText) r.GET("/fmsg/:id/thread/messages", h.ThreadMessages) diff --git a/internal/handlers/hub.go b/internal/handlers/hub.go index 925a188..331f5cf 100644 --- a/internal/handlers/hub.go +++ b/internal/handlers/hub.go @@ -19,6 +19,7 @@ const ( eventDelivered = "delivered" eventRecipientsAdded = "recipients_added" eventReaction = "reaction" + eventEdit = "edit" eventRead = "read" eventTrash = "trash" eventIndicator = "indicator" @@ -51,6 +52,10 @@ type Hub struct { // recipients as a reaction event carrying the refreshed subject, never // as new_msg. reactionSubject func(ctx context.Context, msgID int64) (int64, bool) + // 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) // indicatorAudience reports a message's participants and its thread's // first message, for FMSG-006 indicators. @@ -73,6 +78,7 @@ 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{}), } @@ -191,6 +197,14 @@ func (h *Hub) route(ctx context.Context, channel string, msgID int64, addr strin 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 + } + } // Web Push runs in its own goroutine: 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 diff --git a/internal/handlers/messages.go b/internal/handlers/messages.go index e93ff67..61023eb 100644 --- a/internal/handlers/messages.go +++ b/internal/handlers/messages.go @@ -94,6 +94,8 @@ type messageListItem struct { Attachments []models.Attachment `json:"attachments"` Reaction *string `json:"reaction"` Reactions []models.Reaction `json:"reactions"` + Edit bool `json:"edit"` + Edited *models.Edited `json:"edited"` // Trash is "message" or "thread" when the message is in the caller's // trash, null otherwise. Trash *string `json:"trash"` @@ -428,6 +430,7 @@ func (h *MessageHandler) List(c *gin.Context) { } h.populateListReactions(ctx, messages) + h.populateListEdits(ctx, messages) c.JSON(http.StatusOK, messages) } @@ -538,6 +541,7 @@ func (h *MessageHandler) Sent(c *gin.Context) { } h.populateListReactions(ctx, messages) + h.populateListEdits(ctx, messages) c.JSON(http.StatusOK, messages) } @@ -699,6 +703,15 @@ func (h *MessageHandler) Get(c *gin.Context) { 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) + } + if eff := h.loadEffectiveEdits(ctx, []int64{msgID})[msgID]; eff != nil { + msg.Edited = eff.edited() + if eff.applied { + msg.ShortText = h.shortTextOf(eff.data, msg.Type) + } + } // Populate per-recipient read state for the calling user. The sender // has no read state of their own. @@ -771,6 +784,24 @@ 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 { + name := "data" + if dataPath != "" { + name = filepath.Base(dataPath) + } + contentType := mime.TypeByExtension(filepath.Ext(name)) + if contentType == "" { + contentType = "application/octet-stream" + } + c.Header("Content-Disposition", mime.FormatMediaType("attachment", map[string]string{"filename": name})) + c.Data(http.StatusOK, contentType, eff.data) + return + } + } + if dataPath == "" { c.JSON(http.StatusNotFound, gin.H{"error": "message data not available"}) return @@ -1552,6 +1583,15 @@ func (h *MessageHandler) messageItemFor(ctx context.Context, msgID int64, recipi 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) + } + if eff := h.loadEffectiveEdits(ctx, []int64{msgID})[msgID]; eff != nil { + item.Edited = eff.edited() + if eff.applied { + item.ShortText = h.shortTextOf(eff.data, item.Type) + } + } // Populate the recipient's per-recipient read state, mirroring Get. var timeRead *float64 diff --git a/internal/handlers/push.go b/internal/handlers/push.go index 3ea03e7..c894028 100644 --- a/internal/handlers/push.go +++ b/internal/handlers/push.go @@ -181,6 +181,9 @@ func (h *PushHandler) NotifyNewMsg(_ context.Context, msgID int64, addr string) if item.Reaction != nil { return // FMSG-005: a reaction does not warrant a notification } + if item.Edit { + return // FMSG-008: nor does an edit + } if item.purged || item.Trash != nil { return // in the recipient's trash: they aren't told } diff --git a/internal/handlers/reactions.go b/internal/handlers/reactions.go index fae4c5c..a410fcb 100644 --- a/internal/handlers/reactions.go +++ b/internal/handlers/reactions.go @@ -347,8 +347,9 @@ func (h *MessageHandler) React(c *gin.Context) { recipients := reactionRecipients(subject, identity) if len(recipients) == 0 { - c.JSON(http.StatusConflict, gin.H{"error": "message has no other participants to send a reaction to"}) - return + // A message the caller sent only to themselves: the reaction is + // addressed to the caller (FMSG-005 v0.1.1). + recipients = []string{identity} } // Idempotency: the caller's current effective reaction. diff --git a/internal/handlers/thread.go b/internal/handlers/thread.go index 5246589..4bef22d 100644 --- a/internal/handlers/thread.go +++ b/internal/handlers/thread.go @@ -2,6 +2,7 @@ package handlers import ( "context" + "encoding/hex" "errors" "fmt" "log" @@ -65,6 +66,7 @@ type threadMessage struct { MessageSHA256 string `json:"message_sha256,omitempty"` Trash *string `json:"trash,omitempty"` // "message" or "thread" when in the caller's trash Body *threadBody `json:"body,omitempty"` + Edited *models.Edited `json:"edited,omitempty"` Attachments []threadAttachment `json:"attachments,omitempty"` dataPath string } @@ -269,6 +271,41 @@ 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 { @@ -352,11 +389,25 @@ func (h *MessageHandler) ThreadText(c *gin.Context) { return } + entryIDs := make([]int64, 0, len(entries)) + for i := range entries { + if entries[i].Readable { + entryIDs = append(entryIDs, entries[i].ID) + } + } + edits := h.loadEffectiveEdits(ctx, entryIDs) + 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 @@ -500,6 +551,7 @@ 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/middleware/oauth.go b/internal/middleware/oauth.go index f714fc2..18b37bc 100644 --- a/internal/middleware/oauth.go +++ b/internal/middleware/oauth.go @@ -45,6 +45,7 @@ var oauthRouteScopes = map[string]string{ "POST /fmsg/:id/restore": ScopeWrite, "POST /fmsg/:id/add-to": ScopeWrite, "POST /fmsg/:id/react": ScopeWrite, + "POST /fmsg/:id/edit": ScopeWrite, "POST /fmsg/:id/indicate": ScopeWrite, "POST /fmsg/:id/attach": ScopeWrite, "DELETE /fmsg/:id/attach/:filename": ScopeWrite, diff --git a/internal/models/models.go b/internal/models/models.go index 6660e2d..9788529 100644 --- a/internal/models/models.go +++ b/internal/models/models.go @@ -52,9 +52,19 @@ type Message struct { Attachments []Attachment `json:"attachments"` Reaction *string `json:"reaction"` // FMSG-005: the emoji this message carries when it is a reaction ("" clears); nil otherwise Reactions []Reaction `json:"reactions"` // FMSG-005: effective reactions on this message + Edit bool `json:"edit"` // FMSG-008: whether this message is itself an edit message + Edited *Edited `json:"edited"` // FMSG-008: the effective edit on this message; nil when it has none Trash *string `json:"trash"` // "message" or "thread" when in the caller's trash, null otherwise } +// Edited identifies the edit message in force on a message (FMSG-008) and the +// byte length of the edited data, nil when the edit could not be applied. +type Edited struct { + ID int64 `json:"id"` + Time float64 `json:"time"` + Size *int `json:"size"` +} + // Reaction is one emoji currently reacted on a message and the participants // whose effective reaction it is (FMSG-005). type Reaction struct {