// Copyright (c) 2026 Xessenger // // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. package bridgekit import ( "bytes" "context" "encoding/json" "errors" "fmt" "io" "net/http" "net/url" "regexp" "slices" "strings" "sync" "time" "github.com/rs/zerolog" "maunium.net/go/mautrix" "maunium.net/go/mautrix/appservice" "maunium.net/go/mautrix/bridgev2" "maunium.net/go/mautrix/crypto/attachment" "maunium.net/go/mautrix/event" "maunium.net/go/mautrix/id" ) // The list of the files in encrypted rooms that deletion reads (docs/e2ee/work-plan.md 4.12). A file's // address is inside the Megolm ciphertext there, where neither Synapse's list of a room's files nor the // API's deletion finds it. Every file of the rooms the bridge bridges passes through it, both ways, so // it writes down which events of its encrypted rooms carry which of the homeserver's files: // - a message, edit or sticker it sends into one as the bot, a contact's ghost or a user's double // puppet (what a history move writes among them), once the event has its ID, at the time it gave // the event. An edit's files are written down as the event's it replaces: a deletion on the // messenger redacts that event alone, and an edit of a caption carries the same file again; // - the encrypted room metadata and member profiles (meta.go), in their slot (the outer state key), // with the picture they show or none, which empties the slot; // - a message or sticker the user's app or a member sends into the encrypted room of a portal, once // decrypted; // - the attachments a mail composed in the app lists in its mail.json (com.xessenger.email.compose), // which the bridge reads with the keys the event gives, for the composition's event (one a history // move writes at once, NoteWrittenFiles). The event's own files wait for them: mail.json written // down alone could go with a deleted mail before the attachments are known; // - a redaction in one, of a message deleted on the messenger or in the app: the event's rows go. A // reaction's is left out, as a reaction has no files; // - the files a history move copies into a room, under the move (moveHoldEvent) until it ends: it puts // one copy of a file into every message that carries it, and a message moved earlier may be // deleted on the messenger before the later ones are written, which would take the copy with it. // // It goes to the API, POST and DELETE /api/e2ee/media-refs/bridge, with the bridge's provisioning // secret. What has not gone yet waits in the bridge database (xessenger_e2ee_media_ref; a row the // database did not take is kept in memory and queued again before the next round) and is sent oldest // first, again and again while the API does not take it, waiting longer each time. What the API // refuses for good (400, 403) is dropped, and the rest of its request sent without it. A redaction goes // only once no other row waits, those after it and the mail compositions not read yet included: another // event may show the same file (a history move puts one encrypted copy into every message with that // file, the Telegram bridge gives a sticker it uploaded once again), and the API deletes a file as soon // as no row it has shows it. // apiURLEnv names where the bridge reaches the Xessenger API: in the enclave the host's loopback, on // the local stack the host's. Without it nobody can be switched on (Enable). const apiURLEnv = "XESSENGER_API_URL" const mediaRefsPath = "/api/e2ee/media-refs/bridge" // The parts of an event a row of the queue holds. const ( refEvent = "event" // the event's own files refEdit = "edit:" // followed by an edit's ID: the files of that edit of the event refMail = "mail" // the attachments its mail composition lists refCompose = "compose" // a mail composition to read for its attachments, whose keys it keeps sealed refDelete = "delete" // the event was redacted: its rows go refHold = "hold:" // followed by a media ID: a file a history move holds (HoldMovedFiles) ) // What one request to the API takes (apps/api/src/e2ee/media-refs.ts): files of an event, events, their // files, and bytes (the API takes 256,000). const ( maxEventMedia = 100 maxRequestRefs = 200 maxRequestMedia = 2000 maxRequestBody = 250_000 ) const ( // waitingRefs is how many rows of each kind a round of sending reads. waitingRefs = 500 // refsBackoffMin and refsBackoffMax are how long the sender waits once the API did not take what it // sent: at first, doubled each time, and at most. refsBackoffMin = 5 * time.Second refsBackoffMax = 10 * time.Minute // refsIdle is how long rows that could not go in a round (a mail composition not read) wait when // nothing new comes. refsIdle = 10 * time.Minute // compositionWait is how long a mail composition whose mail.json cannot be downloaded is tried // again: the redactions after it wait for it, and its attachments are given up on after that. compositionWait = 24 * time.Hour ) // errNoMediaRefs refuses to switch somebody on while the bridge cannot write down the files of the // rooms that would be encrypted for them. var errNoMediaRefs = fmt.Errorf("%w: %s is not set, so the files of encrypted rooms could not be listed for deletion", errCannotEnable, apiURLEnv) var mediaIDPattern = regexp.MustCompile(`^[a-zA-Z0-9_-]{5,200}$`) // mediaKeys are the keys under which Matrix content holds the mxc URI of a file: a file's, an encrypted // file's and a thumbnail's, and the picture of a profile or a link preview. var mediaKeys = map[string]bool{"url": true, "thumbnail_url": true, "avatar_url": true, "og:image": true} // composeKey holds a mail composed in the app: its mail.json, encrypted in an encrypted room. const composeKey = "com.xessenger.email.compose" // mediaRef is a row of the queue. type mediaRef struct { RoomID id.RoomID EventID id.EventID Part string MediaIDs []string // OriginTS is when the event was sent, in ms. OriginTS int64 // StateSlot is the outer state key of the encrypted state a picture belongs to, "" for a message. StateSlot string // Composition is the sealed EncryptedFileInfo of a mail composition's mail.json (refCompose). Composition string QueuedAt int64 } // eventFiles is what an event carries that is written down: the homeserver's files, as media IDs, and // the encrypted mail.json of a mail composition. type eventFiles struct { media []string composition *event.EncryptedFileInfo // replaces is the event an edit replaces (m.replace), whose files the edit's are written down as. replaces id.EventID } func (f eventFiles) empty() bool { return len(f.media) == 0 && f.composition == nil } // mediaRefs writes the list down at the API. type mediaRefs struct { kit *Kit url string secret string client *http.Client wake chan struct{} start sync.Once // unkept are rows the bridge database did not take when their event went (unkeep). unkeptLock sync.Mutex unkept []mediaRef } func newMediaRefs(k *Kit, api, secret string) (*mediaRefs, error) { parsed, err := url.Parse(strings.TrimRight(strings.TrimSpace(api), "/")) if err != nil || (parsed.Scheme != "http" && parsed.Scheme != "https") || parsed.Host == "" { return nil, fmt.Errorf("%s must be the Xessenger API's http(s) URL", apiURLEnv) } transport := http.DefaultTransport.(*http.Transport).Clone() transport.Proxy = nil return &mediaRefs{ kit: k, url: parsed.String() + mediaRefsPath, secret: secret, client: &http.Client{Timeout: 30 * time.Second, Transport: transport}, wake: make(chan struct{}, 1), }, nil } // filesOf finds what an event's content carries (eventFiles): the homeserver's files wherever they sit // under mediaKeys (the file, its thumbnail, an edit's, a gallery's images, a link preview's picture, a // per-message profile's picture, an encrypted state's picture, a mail's mail.json), each once and // sorted. Another server's file is not the homeserver's to delete. The HTML of a message is not read: // what it shows inline (custom emoji) is uploaded once for every room. func (k *Kit) filesOf(data []byte) eventFiles { var value any if json.Unmarshal(data, &value) != nil { return eventFiles{} } found := map[string]bool{} k.collectMedia(value, found) files := eventFiles{media: make([]string, 0, len(found))} for mediaID := range found { files.media = append(files.media, mediaID) } slices.Sort(files.media) if object, ok := value.(map[string]any); ok { // A decrypted event has the relation of its encrypted one (mautrix copies it in). if relation, ok := object["m.relates_to"].(map[string]any); ok && relation["rel_type"] == string(event.RelReplace) { if target, ok := relation["event_id"].(string); ok && target != "" { files.replaces = id.EventID(target) } } if compose, ok := object[composeKey].(map[string]any); ok { if raw, ok := compose["file"].(map[string]any); ok { var file event.EncryptedFileInfo if encoded, err := json.Marshal(raw); err == nil && json.Unmarshal(encoded, &file) == nil { if _, local := k.localMedia(string(file.URL)); local { files.composition = &file } } } } } return files } func (k *Kit) collectMedia(value any, found map[string]bool) { switch v := value.(type) { case map[string]any: for key, item := range v { if uri, ok := item.(string); ok { if mediaKeys[key] { if mediaID, local := k.localMedia(uri); local { found[mediaID] = true } } continue } k.collectMedia(item, found) } case []any: for _, item := range v { k.collectMedia(item, found) } } } // localMedia is the media ID of an mxc URI of this homeserver's. func (k *Kit) localMedia(uri string) (string, bool) { if !strings.HasPrefix(uri, "mxc://") { return "", false } parsed, err := id.ContentURIString(uri).Parse() if err != nil || parsed.Homeserver != k.main.Config.Homeserver.Domain || !mediaIDPattern.MatchString(parsed.FileID) { return "", false } return parsed.FileID, true } // sendingFiles is what a message event the bridge sends has written down once it went. It is read // before the send, which encrypts the content in place. type sendingFiles struct { files eventFiles redacts id.EventID } // beforeSend reads what a message event the bridge is about to send would have written down, nil for // nothing. func (k *Kit) beforeSend(eventType event.Type, content *event.Content) *sendingFiles { if k.refs == nil || content == nil { return nil } switch eventType { case event.EventRedaction: if redacts := redactsOf(content); redacts != "" { return &sendingFiles{redacts: redacts} } return nil case event.EventReaction: return nil } data, err := json.Marshal(content) if err != nil { return nil } if files := k.filesOf(data); !files.empty() { return &sendingFiles{files: files} } return nil } func redactsOf(content *event.Content) id.EventID { if parsed, ok := content.Parsed.(*event.RedactionEventContent); ok && parsed.Redacts != "" { return parsed.Redacts } else if raw, ok := content.Raw["redacts"].(string); ok { return id.EventID(raw) } return "" } // afterSend writes down what a message event the bridge sent into an encrypted room carries, at the // time the event was given. func (k *Kit) afterSend(ctx context.Context, roomID id.RoomID, sending *sendingFiles, resp *mautrix.RespSendEvent, extra *bridgev2.MatrixSendExtra) { if sending == nil || !k.encryptedRoom(ctx, roomID) { return } if sending.redacts != "" { k.noteRedaction(ctx, roomID, sending.redacts) return } else if resp == nil || resp.EventID == "" { return } sent := time.Now() if extra != nil && !extra.Timestamp.IsZero() { sent = extra.Timestamp } _ = k.noteFiles(ctx, roomID, resp.EventID, sending.files, sent.UnixMilli()) } // noteState writes down the picture of the encrypted state the bridge sent into a room (meta.go), in // its slot: none empties it. func (k *Kit) noteState(ctx context.Context, roomID id.RoomID, eventID id.EventID, slot string, content []byte) error { if k.refs == nil || eventID == "" { return nil } return k.queueRefs(ctx, []mediaRef{{ RoomID: roomID, EventID: eventID, Part: refEvent, MediaIDs: k.capMedia(ctx, roomID, eventID, k.filesOf(content).media), OriginTS: time.Now().UnixMilli(), StateSlot: slot, }}) } // installMediaRefs puts noteReceived in front of bridgev2's Matrix event handlers and of the extension's // (refuse.go, membersend.go), which may hand an event on as somebody else's. func (k *Kit) installMediaRefs() { for _, eventType := range []event.Type{event.EventMessage, event.EventSticker, event.EventRedaction} { k.conn.EventProcessor.PrependHandler(eventType, k.noteReceived) } } // noteReceived writes down what the user's app or a member sent into the encrypted room of a portal: // the files of a message or sticker, once decrypted, and a redaction. It runs before bridgev2 handles // the event. An event the bridge sent itself through a double puppet comes back too, written down when // it went (ownEcho). func (k *Kit) noteReceived(ctx context.Context, evt *event.Event) { if k.refs == nil || !k.isHomeserverUser(evt.Sender) { return } switch evt.Type { case event.EventRedaction: redacts := evt.Redacts if redacts == "" { redacts = redactsOf(&evt.Content) } if redacts != "" && k.encryptedRoom(ctx, evt.RoomID) && k.portalRoom(ctx, evt.RoomID) { k.noteRedaction(ctx, evt.RoomID, redacts) } case event.EventMessage, event.EventSticker: if !evt.Mautrix.WasEncrypted || k.ownEcho(evt) { return } data := []byte(evt.Content.VeryRaw) if len(data) == 0 { var err error if data, err = json.Marshal(&evt.Content); err != nil { return } } if files := k.filesOf(data); !files.empty() && k.portalRoom(ctx, evt.RoomID) { _ = k.noteFiles(ctx, evt.RoomID, evt.ID, files, evt.Timestamp) } } } // The history move asks the connector for NoteWrittenFiles in this shape (migrate's fileNoter). var _ interface { NoteWrittenFiles(ctx context.Context, roomID id.RoomID, eventID id.EventID, content json.RawMessage, sent time.Time) error } = (*connector)(nil) // The history move asks the connector for HoldMovedFiles and ReleaseMovedFiles in this shape (migrate's // fileHolder). var _ interface { HoldMovedFiles(ctx context.Context, roomID, oldRoom id.RoomID, files []id.ContentURIString) error ReleaseMovedFiles(ctx context.Context, roomID, oldRoom id.RoomID) error } = (*connector)(nil) // moveHoldEvent is the event a history move from oldRoom holds the files it copied under // (HoldMovedFiles). No Matrix event takes this ID; the API takes it as any other. func moveHoldEvent(oldRoom id.RoomID) id.EventID { return id.EventID("$xessenger-move:" + string(oldRoom)) } // HoldMovedFiles writes down the files a history move from oldRoom copied into roomID under the move // (moveHoldEvent), before any message shows them: the move puts one copy of a file into every message // that carries it, and a message moved earlier may be deleted on the messenger before the later ones // are written, which would take the copy with it. ReleaseMovedFiles lets go of them once the move is // done; a move that never ends lets go of them with the room's retention. An error is the bridge // database's. func (c *connector) HoldMovedFiles(ctx context.Context, roomID, oldRoom id.RoomID, files []id.ContentURIString) error { k := c.kit if k.refs == nil { return nil } hold, now := moveHoldEvent(oldRoom), time.Now().UnixMilli() var refs []mediaRef for _, file := range files { if mediaID, ok := k.localMedia(string(file)); ok { refs = append(refs, mediaRef{RoomID: roomID, EventID: hold, Part: refHold + mediaID, MediaIDs: []string{mediaID}, OriginTS: now}) } } return k.queueRefs(ctx, refs) } // ReleaseMovedFiles lets go of the files a history move from oldRoom held (HoldMovedFiles) once it is // done: those none of its messages shows go. The redaction goes after all that came before it, the // moved messages' files among them. An error is the bridge database's. func (c *connector) ReleaseMovedFiles(ctx context.Context, roomID, oldRoom id.RoomID) error { k := c.kit if k.refs == nil { return nil } return k.queueRefs(ctx, []mediaRef{{RoomID: roomID, EventID: moveHoldEvent(oldRoom), Part: refDelete, MediaIDs: []string{}, OriginTS: time.Now().UnixMilli()}}) } // NoteWrittenFiles keeps the files of an event a history move wrote into a room, or found written there // after the bridge stopped (migrate's findWritten), to write down before the move notes the event as // written: what it carries may not have been kept as it went. A moved mail's attachments are read from // its mail.json at once, not when the queue gets to it: the move lets go of the copies it made once it // is done (ReleaseMovedFiles), and a mail.json the queue gave up on reading would leave the copies of // the attachments to be deleted. An error is the bridge database's, or a download of the mail.json // that may work later. func (c *connector) NoteWrittenFiles(ctx context.Context, roomID id.RoomID, eventID id.EventID, content json.RawMessage, sent time.Time) error { k := c.kit if k.refs == nil || !k.encryptedRoom(ctx, roomID) { return nil } files := k.filesOf(content) if files.composition != nil && files.replaces == "" { return k.noteComposition(ctx, roomID, eventID, files, sent.UnixMilli()) } else if !files.empty() { return k.noteFiles(ctx, roomID, eventID, files, sent.UnixMilli()) } return nil } // noteComposition keeps an event's files to write down with the attachments of its mail composition, // whose mail.json it reads now. One gone or that does not decrypt leaves the event's own files. func (k *Kit) noteComposition(ctx context.Context, roomID id.RoomID, eventID id.EventID, files eventFiles, originTS int64) error { ref := mediaRef{RoomID: roomID, EventID: eventID, MediaIDs: k.capMedia(ctx, roomID, eventID, files.media), OriginTS: originTS} file := *files.composition var attachments []string if data, err := k.br.Bot.DownloadMedia(ctx, file.URL, &file); err == nil { attachments = k.compositionMedia(ctx, ref, data) } else if !downloadGone(err) { return fmt.Errorf("failed to download a moved mail composition for its attachments: %w", err) } else { zerolog.Ctx(ctx).Warn().Err(err).Stringer("room_id", roomID).Stringer("event_id", eventID). Msg("A moved mail composition is gone or does not decrypt; its attachments are not written down") } return k.queueRefs(ctx, compositionRows(ref, attachments)) } // noteFiles keeps an event's files to write down, and its mail composition to read, with which its own // files wait. An edit's files are kept as the event's it replaces, in a row of the edit's own (the // event's may still wait); an edit composes no mail. func (k *Kit) noteFiles(ctx context.Context, roomID id.RoomID, eventID id.EventID, files eventFiles, originTS int64) error { part := refEvent if files.replaces != "" { part, eventID, files.composition = refEdit+string(eventID), files.replaces, nil } media := k.capMedia(ctx, roomID, eventID, files.media) if files.composition != nil { sealed, err := k.sealComposition(roomID, eventID, files.composition) if err == nil { return k.queueRefs(ctx, []mediaRef{{RoomID: roomID, EventID: eventID, Part: refCompose, MediaIDs: media, OriginTS: originTS, Composition: sealed}}) } zerolog.Ctx(ctx).Err(err).Stringer("room_id", roomID).Stringer("event_id", eventID).Msg("Failed to keep a mail composition to read for its attachments") } if len(media) == 0 { return nil } return k.queueRefs(ctx, []mediaRef{{RoomID: roomID, EventID: eventID, Part: part, MediaIDs: media, OriginTS: originTS}}) } // noteRedaction takes a redacted event's rows away, unless it was a reaction, which has none. func (k *Kit) noteRedaction(ctx context.Context, roomID id.RoomID, redacts id.EventID) { if k.isReaction(ctx, redacts) { return } _ = k.queueRefs(ctx, []mediaRef{{RoomID: roomID, EventID: redacts, Part: refDelete, MediaIDs: []string{}, OriginTS: time.Now().UnixMilli()}}) } // capMedia keeps the files the API takes of one event (none carries more). func (k *Kit) capMedia(ctx context.Context, roomID id.RoomID, eventID id.EventID, media []string) []string { if media == nil { return []string{} } else if len(media) > maxEventMedia { zerolog.Ctx(ctx).Warn().Stringer("room_id", roomID).Stringer("event_id", eventID).Int("files", len(media)). Msg("An event of an encrypted room carries more files than the API takes; the rest are not written down") return media[:maxEventMedia] } return media } func (k *Kit) queueRefs(ctx context.Context, refs []mediaRef) error { if len(refs) == 0 { return nil } now := time.Now().UnixNano() for i := range refs { if refs[i].QueuedAt == 0 { refs[i].QueuedAt = now + int64(i) } } err := k.store.queueMediaRefs(ctx, refs) if err != nil { zerolog.Ctx(ctx).Err(err).Stringer("room_id", refs[0].RoomID).Stringer("event_id", refs[0].EventID). Msg("Failed to keep the files of an encrypted room's event to write down for deletion; keeping them again later") k.refs.unkeep(refs) } k.refs.startSending(k.backgroundContext()) select { case k.refs.wake <- struct{}{}: default: } return err } // unkeep holds rows the bridge database did not take, for the next round to queue in their place // (queueUnkept): the event went all the same, and what it carries is written down once the database // takes them. They are lost if the bridge stops first. func (r *mediaRefs) unkeep(refs []mediaRef) { if r == nil { return } r.unkeptLock.Lock() r.unkept = append(r.unkept, refs...) r.unkeptLock.Unlock() } // queueUnkept queues the rows the bridge database did not take before (unkeep). func (r *mediaRefs) queueUnkept(ctx context.Context) error { r.unkeptLock.Lock() defer r.unkeptLock.Unlock() if len(r.unkept) == 0 { return nil } else if err := r.kit.store.queueMediaRefs(ctx, r.unkept); err != nil { return err } r.unkept = nil return nil } // encryptedRoom reports whether a room is encrypted, whoever it is for: a history move writes encrypted // Xessenger rooms nobody may be switched on for here, which isEncrypted does not ask about. A room whose // state cannot be read counts as encrypted: the files of a plaintext room written down are let go of // with the room all the same. func (k *Kit) encryptedRoom(ctx context.Context, roomID id.RoomID) bool { if _, ok := k.encrypted.Load(roomID); ok { return true } encrypted, err := k.conn.StateStore.IsEncrypted(ctx, roomID) if err != nil { return true } else if encrypted { k.markEncrypted(roomID) } return encrypted } // portalRoom reports whether a room is a portal's: other rooms the bot shares with a user (its // management room) hold nothing the API deletes. func (k *Kit) portalRoom(ctx context.Context, roomID id.RoomID) bool { if k.br == nil { return false } portal, err := k.br.GetPortalByMXID(ctx, roomID) return err == nil && portal != nil } // isReaction reports whether bridgev2 knows an event as a reaction. bridgev2 forgets a reaction after // its redaction went to Matrix, and handles one from Matrix after noteReceived. func (k *Kit) isReaction(ctx context.Context, eventID id.EventID) bool { if k.br == nil || k.br.DB == nil { return false } reaction, err := k.br.DB.Reaction.GetByMXID(ctx, eventID) return err == nil && reaction != nil } // ownEcho reports whether an event is one the bridge sent through a double puppet, as bridgev2 tells // (its Connector.shouldIgnoreEvent drops them). func (k *Kit) ownEcho(evt *event.Event) bool { if k.conn == nil || k.conn.AS == nil || k.conn.AS.DoublePuppetValue == "" { return false } if value, ok := evt.Content.Raw[appservice.DoublePuppetKey]; !ok || value != k.conn.AS.DoublePuppetValue { return false } ts, ok := evt.Content.Raw[appservice.DoublePuppetTSKey].(float64) return !ok || int64(ts) == evt.Timestamp } func (k *Kit) compositionContext(roomID id.RoomID, eventID id.EventID) string { return k.store.sealContext("media-ref-composition", string(roomID)+"\x00"+string(eventID)) } func (k *Kit) sealComposition(roomID id.RoomID, eventID id.EventID, file *event.EncryptedFileInfo) (string, error) { if !k.box.Ready() { return "", errors.New("the bridge has no store key to keep the keys of a mail composition with") } data, err := json.Marshal(file) if err != nil { return "", err } return k.box.Seal(k.compositionContext(roomID, eventID), data) } // startSending starts the sender once, which runs until ctx ends. func (r *mediaRefs) startSending(ctx context.Context) { if r == nil { return } r.start.Do(func() { go r.run(ctx) }) } // run sends what waits, a round at a time: at once when a round sent anything, otherwise once something // new waits. After the API did not take what was sent it waits, longer each time, and what comes // meanwhile waits with it. func (r *mediaRefs) run(ctx context.Context) { backoff := time.Duration(0) for { progress, err := r.round(ctx) if ctx.Err() != nil { return } wait := refsIdle if err != nil { backoff = min(max(2*backoff, refsBackoffMin), refsBackoffMax) wait = backoff zerolog.Ctx(ctx).Warn().Err(err).Dur("retry_in", backoff).Msg("The files of encrypted rooms did not reach the Xessenger API; sending them again later") } else if backoff = 0; progress { continue } timer := time.NewTimer(wait) select { case <-ctx.Done(): case <-timer.C: case <-r.wake: if err != nil { select { case <-ctx.Done(): case <-timer.C: } } } timer.Stop() if ctx.Err() != nil { return } } } // round reads the mail compositions waiting and sends the files waiting, oldest first, and then the // redactions, once nothing else waits: what a redaction lets go of may be named by a row after it too // (one encrypted copy a history move put into every message with the file, a sticker the bridge uploaded // once and gives again, an attachment of a mail composition not read yet), and the API deletes a file // as soon as no row names it. It reports whether any row went, and an error once the API did not take // what it sent. func (r *mediaRefs) round(ctx context.Context) (bool, error) { store := r.kit.store progress := false if err := r.queueUnkept(ctx); err != nil { return false, fmt.Errorf("failed to keep the rows the bridge database did not take: %w", err) } compositions, err := store.waitingMediaRefs(ctx, refCompose, waitingRefs) if err != nil { return false, fmt.Errorf("failed to read the mail compositions waiting: %w", err) } for _, ref := range compositions { if r.readComposition(ctx, ref) { progress = true } } writes, err := store.waitingMediaRefs(ctx, "", waitingRefs) if err != nil { return progress, fmt.Errorf("failed to read the files waiting: %w", err) } for len(writes) > 0 { n := requestSize(writes) if err = r.post(ctx, writes[:n]); err != nil { return progress, err } progress, writes = true, writes[n:] } deletes, err := store.waitingMediaRefs(ctx, refDelete, waitingRefs) if err != nil { return progress, fmt.Errorf("failed to read the redactions waiting: %w", err) } for _, ref := range deletes { // The files past those read, and what came meanwhile, go first: the next round. if others, err := r.othersWaiting(ctx); err != nil || others { return progress, err } else if err = r.deleteRef(ctx, ref); err != nil { return progress, err } progress = true } return progress, nil } // othersWaiting reports whether a row other than a redaction waits: one the bridge database did not // take yet, or one in it. func (r *mediaRefs) othersWaiting(ctx context.Context) (bool, error) { r.unkeptLock.Lock() unkept := len(r.unkept) > 0 r.unkeptLock.Unlock() if unkept { return true, nil } waiting, err := r.kit.store.mediaRefsBesides(ctx, refDelete) if err != nil { return false, fmt.Errorf("failed to read the rows waiting: %w", err) } return waiting, nil } // refBody is a row as the API takes it. type refBody struct { RoomID id.RoomID `json:"roomId"` EventID id.EventID `json:"eventId"` MediaIDs []string `json:"mediaIds"` OriginTS int64 `json:"originTs"` StateSlot string `json:"stateSlot,omitempty"` } func bodyOf(ref mediaRef) refBody { media := ref.MediaIDs if media == nil { media = []string{} } return refBody{RoomID: ref.RoomID, EventID: ref.EventID, MediaIDs: media, OriginTS: ref.OriginTS, StateSlot: ref.StateSlot} } // requestSize is how many of the rows, from the first, one request takes (at least one). func requestSize(refs []mediaRef) int { size, media := len(`{"refs":[]}`), 0 for i, ref := range refs { encoded, _ := json.Marshal(bodyOf(ref)) size += len(encoded) + 1 media += len(ref.MediaIDs) if i > 0 && (i >= maxRequestRefs || size > maxRequestBody || media > maxRequestMedia) { return i } } return len(refs) } // post writes rows down. What the API refuses for good (400, 403: a file it does not take, a room of // another messenger's) goes again in halves, down to the row it refuses, which is dropped. func (r *mediaRefs) post(ctx context.Context, refs []mediaRef) error { bodies := make([]refBody, len(refs)) for i, ref := range refs { bodies[i] = bodyOf(ref) } status, err := r.send(ctx, http.MethodPost, map[string]any{"refs": bodies}) switch { case err != nil: return err case status == http.StatusBadRequest || status == http.StatusForbidden: if len(refs) > 1 { if err = r.post(ctx, refs[:len(refs)/2]); err != nil { return err } return r.post(ctx, refs[len(refs)/2:]) } zerolog.Ctx(ctx).Warn().Int("status", status).Stringer("room_id", refs[0].RoomID).Stringer("event_id", refs[0].EventID). Msg("The Xessenger API refuses the files of an encrypted room's event for good; dropping them") fallthrough case status >= 200 && status < 300: if err = r.kit.store.deleteMediaRefs(ctx, refs); err != nil { return fmt.Errorf("failed to forget the files written down: %w", err) } return nil default: return fmt.Errorf("the Xessenger API answered %d", status) } } // deleteRef takes a redacted event's rows away at the API. func (r *mediaRefs) deleteRef(ctx context.Context, ref mediaRef) error { status, err := r.send(ctx, http.MethodDelete, map[string]string{"roomId": string(ref.RoomID), "eventId": string(ref.EventID)}) switch { case err != nil: return err case status == http.StatusBadRequest || status == http.StatusForbidden: zerolog.Ctx(ctx).Warn().Int("status", status).Stringer("room_id", ref.RoomID).Stringer("event_id", ref.EventID). Msg("The Xessenger API refuses a redaction of an encrypted room for good; dropping it") fallthrough case status >= 200 && status < 300: if err = r.kit.store.deleteMediaRefs(ctx, []mediaRef{ref}); err != nil { return fmt.Errorf("failed to forget the redaction written down: %w", err) } return nil default: return fmt.Errorf("the Xessenger API answered %d", status) } } func (r *mediaRefs) send(ctx context.Context, method string, body any) (int, error) { data, err := json.Marshal(body) if err != nil { return 0, err } req, err := http.NewRequestWithContext(ctx, method, r.url, bytes.NewReader(data)) if err != nil { return 0, err } req.Header.Set("Authorization", "Bearer "+r.secret) req.Header.Set("Content-Type", "application/json") resp, err := r.client.Do(req) if err != nil { return 0, err } defer resp.Body.Close() _, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, 64<<10)) return resp.StatusCode, nil } // readComposition puts the rows of a mail composition's event in its place, where it waited: the event's // own files and the attachments its mail.json lists. mail.json is downloaded and decrypted with the keys // the event gave, which the row keeps sealed. A mail.json the homeserver no longer has, or that does not // decrypt or read, leaves the event's own files. One that cannot be downloaded now is tried again the // next round, for compositionWait at most. It reports whether the row went. func (r *mediaRefs) readComposition(ctx context.Context, ref mediaRef) bool { k := r.kit log := zerolog.Ctx(ctx).With().Stringer("room_id", ref.RoomID).Stringer("event_id", ref.EventID).Logger() var file event.EncryptedFileInfo data, err := k.box.Open(k.compositionContext(ref.RoomID, ref.EventID), ref.Composition) if err == nil { err = json.Unmarshal(data, &file) } var attachments []string if err != nil { log.Err(err).Msg("Failed to open the keys of a mail composition; its attachments are not written down") } else if data, err = k.br.Bot.DownloadMedia(ctx, file.URL, &file); err == nil { attachments = k.compositionMedia(ctx, ref, data) } else if !downloadGone(err) && time.Since(time.Unix(0, ref.QueuedAt)) < compositionWait { log.Err(err).Msg("Failed to download a mail composition for its attachments; trying again later") return false } else { log.Warn().Err(err).Msg("A mail composition is gone, does not decrypt or could not be downloaded for a day; its attachments are not written down") } if err = k.store.replaceMediaRef(ctx, ref, compositionRows(ref, attachments)); err != nil { log.Err(err).Msg("Failed to keep the files of a mail composition to write down") return false } return true } // compositionRows are the rows a read mail composition is written down as: the event's own files, and // the attachments its mail.json lists. func compositionRows(ref mediaRef, attachments []string) []mediaRef { var rows []mediaRef if len(ref.MediaIDs) > 0 { rows = append(rows, mediaRef{RoomID: ref.RoomID, EventID: ref.EventID, Part: refEvent, MediaIDs: ref.MediaIDs, OriginTS: ref.OriginTS}) } if len(attachments) > 0 { rows = append(rows, mediaRef{RoomID: ref.RoomID, EventID: ref.EventID, Part: refMail, MediaIDs: attachments, OriginTS: ref.OriginTS}) } return rows } // downloadGone reports whether a download failed for good: the file is gone, or does not decrypt. func downloadGone(err error) bool { if notFound(err) { return true } for _, undecryptable := range []error{id.ErrInvalidContentURI, attachment.ErrHashMismatch, attachment.ErrUnsupportedVersion, attachment.ErrUnsupportedAlgorithm, attachment.ErrInvalidKey, attachment.ErrInvalidInitVector, attachment.ErrInvalidHash} { if errors.Is(err, undecryptable) { return true } } return false } // notFound reports whether the homeserver answered that it does not have a file. func notFound(err error) bool { var httpErr mautrix.HTTPError return errors.Is(err, mautrix.MNotFound) || (errors.As(err, &httpErr) && httpErr.Response != nil && httpErr.Response.StatusCode == http.StatusNotFound) } // compositionMedia is the homeserver's files a mail.json lists as attachments ({file | url, ...}). func (k *Kit) compositionMedia(ctx context.Context, ref mediaRef, data []byte) []string { var mail struct { Attachments json.RawMessage `json:"attachments"` } if json.Unmarshal(data, &mail) != nil || len(mail.Attachments) == 0 { return nil } wrapped, err := json.Marshal(map[string]json.RawMessage{"attachments": mail.Attachments}) if err != nil { return nil } return k.capMedia(ctx, ref.RoomID, ref.EventID, k.filesOf(wrapped).media) }