package migrate import ( "context" "fmt" "github.com/rs/zerolog" "maunium.net/go/mautrix" "maunium.net/go/mautrix/appservice" "maunium.net/go/mautrix/event" "maunium.net/go/mautrix/id" ) // A portal's new room is its user's: bridgev2 brings them in as it makes the room (syncParticipants, // the user's own member among the chat's), and the keys of what is written there go only to the // devices of those in the room (crypto's GetRoomJoinedOrInvitedMembers). That sync goes member by // member in no set order, each one a few calls to the homeserver, and stops where the call making the // room was cut short (the API gave up waiting, or its process restarted): the move called again found // the room made and finished it, and the user, not reached yet, stayed out (QA-289: mail threads with // many addresses, the room made in the enclave at a few seconds a call). The history then went into a // room they were not in, under keys none of their devices got, and the read position the API carries // over was refused (M_FORBIDDEN). So the user is brought in whenever the move is finished or told who // reads it, and before anything is said of its history; a history written while they were not in the // room is written again. // ensureUser brings `userID` into the new room as themself, invited by the bot and joined through the // double puppet appservice the bridges share, unless the homeserver has them joined already. The session // the bridge encrypts the room's events with may be one made before, without them, and the homeserver's // word of the invite, which ends it (crypto's HandleMemberEvent), reaches the bridge only some time // after. So it is ended here (resetSession) before the invite, which sends the room's metadata at once // (bridgekit's memberArrived): the next session is made for those the state store has in the room then, // the user invited among them. The room's name went in the old one before, out of their devices' reach // (QA-289). It is ended again once they joined, for the history that follows. func (m *mover) ensureUser(ctx context.Context, roomID id.RoomID, userID id.UserID) error { joined, err := m.conn.Bot.JoinedMembers(ctx, roomID) if err != nil { return fmt.Errorf("failed to read the new room's members: %w", err) } if _, ok := joined.Joined[userID]; ok { return nil } m.resetSession(ctx, roomID) if err = m.br.Bot.EnsureInvited(ctx, roomID, userID); err != nil { return fmt.Errorf("failed to invite the user into the new room: %w", err) } if err = m.joinAsUser(ctx, roomID, userID); err != nil { return fmt.Errorf("failed to join the user to the new room: %w", err) } m.resetSession(ctx, roomID) zerolog.Ctx(ctx).Info().Stringer("new_room_id", roomID).Msg("Brought a moved portal's user into its new room") return nil } // joinAsUser joins a room as the user, through their double puppet (joinUser stands in for it in tests). // The bot invites them again if the homeserver refuses the join. func (m *mover) joinAsUser(ctx context.Context, roomID id.RoomID, userID id.UserID) error { if m.joinUser != nil { return m.joinUser(ctx, roomID, userID) } intent, err := m.doublePuppet(ctx, userID) if err != nil { return err } return intent.EnsureJoined(ctx, roomID, appservice.EnsureJoinedParams{IgnoreCache: true}) } // resetSession ends the Megolm session the bridge encrypts the room's events with: the next one is made // for those the state store has in the room then, and its keys go to their devices. func (m *mover) resetSession(ctx context.Context, roomID id.RoomID) { if m.conn.Crypto != nil { m.conn.Crypto.ResetSession(ctx, roomID) } } // keepUser makes sure a portal's user is in its new room before the API is told anything about its // history: a history written before they were in the room is set to be written again (setAside), and // they are brought in (ensureUser). A failure for a person to look at (errSelfCheck) stays as it is. // Called under the room's lock, while no job of it runs. func (m *mover) keepUser(ctx context.Context, row *room) error { if row.Kind != kindPortal || row.NewRoom == "" || (row.State == stateFailed && row.Error == errSelfCheck) { return nil } written, err := m.store.events(ctx, row.OldRoom) if err != nil { return err } unkept, err := m.unkept(ctx, row, len(written)) if err != nil { return err } if first := firstWritten(written, unkept); first != "" { without, err := m.writtenWithoutUser(ctx, row, first) if err != nil { return err } else if without { if err = m.setAside(ctx, row, written, unkept); err != nil { return err } } } return m.ensureUser(ctx, row.NewRoom, row.User) } // unkept looks for the event a run was writing when it ended, if it ended after sending it and before // keeping it (AttemptSeq one past the last kept event, as migrate looks for it with findWritten): it // went out under the keys the history did, and is part of what it wrote. Nil for none. func (m *mover) unkept(ctx context.Context, row *room, kept int) (*staleEvent, error) { if row.AttemptSeq != kept+1 { return nil, nil } evt, content, err := m.readBack(ctx, row, row.AttemptSeq, func(Marker) bool { return true }) if err != nil || evt == nil { return nil, err } marker, _ := MarkerOf(content) return &staleEvent{NewEventID: evt.ID, OldEventID: id.EventID(marker.From)}, nil } // firstWritten is the first event a history wrote into its new room: the first one kept, or the one sent // without being kept when none was. func firstWritten(written []*movedEvent, unkept *staleEvent) id.EventID { if len(written) > 0 { return written[0].NewEventID } else if unkept != nil { return unkept.NewEventID } return "" } // writtenWithoutUser reads a portal's new room from its start up to the first event its history wrote // and reports whether its user was not in the room then: no invite or join of theirs held when it was // written. None of their devices got the keys it went out under, and one who came in only since // (bridgev2's member sync, a move called again) did not either. A room whose first written event is not // found as read tells nothing, and its history is left as it is. func (m *mover) writtenWithoutUser(ctx context.Context, row *room, first id.EventID) (bool, error) { membership, found := "", false err := m.readFromStart(ctx, row.NewRoom, func(evt *event.Event) bool { if evt.ID == first { found = true return false } if evt.Type == event.StateMember && evt.StateKey != nil && id.UserID(*evt.StateKey) == row.User { membership, _ = evt.Content.Raw["membership"].(string) } return true }) if err != nil { return false, err } else if !found { zerolog.Ctx(ctx).Warn().Stringer("new_room_id", row.NewRoom). Msg("The first event a moved history wrote is not in its new room as read; the history stays as it is") return false, nil } return membership != string(event.MembershipJoin) && membership != string(event.MembershipInvite), nil } // readFromStart reads a room's member and encrypted events from its start, in timeline order, until // visit says to stop or the room ends (at most maxEvents). func (m *mover) readFromStart(ctx context.Context, roomID id.RoomID, visit func(*event.Event) bool) error { filter := &mautrix.FilterPart{Types: []event.Type{event.StateMember, event.EventEncrypted}} from := "" for range maxEvents / readBackPage { page, err := m.conn.Bot.Messages(ctx, roomID, from, "", mautrix.DirectionForward, filter, readBackPage) if err != nil { return fmt.Errorf("failed to read the new room: %w", err) } for _, evt := range page.Chunk { if !visit(evt) { return nil } } // As in readRoom, an empty page with an end reads on. if page.End == "" || page.End == from { return nil } from = page.End } return nil } // setAside sets a portal's history written before its user was in the new room to be written again, // from its first event, once they are (keepUser). In one transaction, bridgev2's records of its // messages point back at the old room's events, as before the history moved (the run points them at // what it writes); the events it wrote are kept as copies to delete once the history is written again // (redactStale), which until then name the files it shows again (deleted now, they would let those go, // mediarefs.go); and the move's numbers go. The room's digest key and the copied files stay for the run. // A copy deleted since (the message taken back) has its copy written again deleted too. The event sent // without being kept (unkept), whose record still names the old room's event, is a copy as well: the // run written again would otherwise not know it, and leave it in the room besides what it writes. func (m *mover) setAside(ctx context.Context, row *room, written []*movedEvent, unkept *staleEvent) error { deleted, err := m.deletedCopies(ctx, row, written) if err != nil { return err } stale := make([]staleEvent, 0, len(written)+1) for _, e := range written { stale = append(stale, staleEvent{NewEventID: e.NewEventID, OldEventID: e.OldEventID, Deleted: deleted[e.NewEventID]}) } if unkept != nil { stale = append(stale, *unkept) } next := *row next.State, next.Error, next.AttemptSeq = stateMoved, "", 0 next.Events, next.Files, next.Digest, next.MissingFiles = 0, 0, "", 0 next.MailCompose, next.LastEventID = false, "" err = m.store.db.DoTxn(ctx, nil, func(ctx context.Context) error { for _, e := range written { if err := m.pointBack(ctx, e); err != nil { return err } } return m.store.setAside(ctx, &next, stale) }) if err != nil { return err } *row = next zerolog.Ctx(ctx).Warn().Stringer("old_room_id", row.OldRoom).Stringer("new_room_id", row.NewRoom). Int("events", len(stale)).Int("deleted", len(deleted)). Msg("Writing a moved history again: it went into the new room before its user was in it") return nil } // deletedCopies reads a portal's new room from its start through the events its history wrote and // returns those deleted since (redacted, or marked so by handleRedacted). func (m *mover) deletedCopies(ctx context.Context, row *room, written []*movedEvent) (map[id.EventID]bool, error) { ids := make(map[id.EventID]bool, len(written)) deleted := map[id.EventID]bool{} if len(written) == 0 { return deleted, nil } for _, e := range written { ids[e.NewEventID] = true if e.Redacted { deleted[e.NewEventID] = true } } seen := 0 err := m.readFromStart(ctx, row.NewRoom, func(evt *event.Event) bool { if ids[evt.ID] { seen++ if evt.Unsigned.RedactedBecause != nil { deleted[evt.ID] = true } } return seen < len(ids) }) return deleted, err } // pointBack makes bridgev2's record of a moved message or reaction name the old room's event again, as it // did before the history moved (repoint the other way). One no record names is left alone. func (m *mover) pointBack(ctx context.Context, e *movedEvent) error { message, err := m.br.DB.Message.GetPartByMXID(ctx, e.NewEventID) if err != nil { return fmt.Errorf("failed to read the record of message %d: %w", e.Seq, err) } else if message != nil { message.MXID = e.OldEventID if err = m.br.DB.Message.Update(ctx, message); err != nil { return fmt.Errorf("failed to point message %d back at its old event: %w", e.Seq, err) } return nil } reaction, err := m.br.DB.Reaction.GetByMXID(ctx, e.NewEventID) if err != nil { return fmt.Errorf("failed to read the record of reaction %d: %w", e.Seq, err) } else if reaction != nil { reaction.MXID = e.OldEventID if err = m.br.DB.Reaction.Upsert(ctx, reaction); err != nil { return fmt.Errorf("failed to point reaction %d back at its old event: %w", e.Seq, err) } } return nil } // redact deletes an event of the new room as the bot, through bridgekit, which lets the files it carried // go (mediarefs.go). func (m *mover) redact(ctx context.Context, roomID id.RoomID, eventID id.EventID) error { redaction := &event.Content{Parsed: &event.RedactionEventContent{Redacts: eventID}} _, err := m.br.Bot.SendMessage(ctx, roomID, event.EventRedaction, redaction, nil) return err } // redactStale deletes the copies a history wrote before its user was in the new room (setAside), once // it is written again: until now they named the files the history written again shows too. The copy // written again of a message taken back before is deleted too, if the run did not get to it (it deletes // one as it writes it). One that cannot be deleted stops the move before it is saved as done, and the // retry deletes the rest. func (m *mover) redactStale(ctx context.Context, row *room, written []*movedEvent) error { stale, err := m.store.staleEvents(ctx, row.OldRoom) if err != nil { return fail(errStore, err) } else if len(stale) == 0 { return nil } byOld := make(map[id.EventID]*movedEvent, len(written)) for _, e := range written { byOld[e.OldEventID] = e } for _, s := range stale { if s.Deleted { if err = m.redactAgain(ctx, row, byOld[s.OldEventID]); err != nil { return err } } else if err = m.redact(ctx, row.NewRoom, s.NewEventID); err != nil { return fail(errSend, fmt.Errorf("failed to delete a copy written before the room's user was in it: %w", err)) } if err = m.store.dropStale(ctx, row.OldRoom, s.NewEventID); err != nil { return fail(errStore, err) } } zerolog.Ctx(ctx).Info().Stringer("old_room_id", row.OldRoom).Stringer("new_room_id", row.NewRoom).Int("deleted", len(stale)). Msg("Deleted the copies a moved history wrote before its user was in the new room") return nil } // redactAgain deletes the copy written again of a message whose earlier copy was deleted (taken back on // the messenger, or by the person) before the history was set to be written again, and marks it so: it // went then, and goes again. None written, or one deleted already, is left alone. func (m *mover) redactAgain(ctx context.Context, row *room, e *movedEvent) error { if e == nil || e.Redacted { return nil } if err := m.redact(ctx, row.NewRoom, e.NewEventID); err != nil { return fail(errSend, fmt.Errorf("failed to delete event %d, deleted before it was written again: %w", e.Seq, err)) } if err := m.store.markRedacted(ctx, row.OldRoom, []int{e.Seq}); err != nil { return fail(errStore, err) } e.Redacted = true return nil }