package migrate import ( "context" "encoding/json" "errors" "fmt" "net/http" "slices" "strings" "time" "github.com/rs/zerolog" "maunium.net/go/mautrix/bridgev2" "maunium.net/go/mautrix/bridgev2/networkid" "maunium.net/go/mautrix/event" "maunium.net/go/mautrix/id" "xessenger/bridgekit/internal/steptimer" ) type moveRequest struct { // Members are the Xessenger identities that get the moved history: for a portal, those sharing // the connection, the user among them or not (the API joins them before migrate, and gives them // again before each start or retry of it: retakePortalMembers); for two Xessenger users' room, // both of them. Members []id.UserID `json:"members"` // NewRoomID is set for two Xessenger users' room: the API made the new room (as one of them, the // way a new Xessenger room is made), joined both and invited this bridge's bot. NewRoomID id.RoomID `json:"newRoomId"` } // handleMove gives an old room its new, encrypted room. Calling it again gives the same room. func (m *mover) handleMove(w http.ResponseWriter, r *http.Request) { userID, ok := m.pathUser(w, r) if !ok { return } oldRoom, ok := pathRoom(w, r) if !ok { return } var req moveRequest if !readBody(w, r, &req) { return } for _, member := range req.Members { if _, server, err := member.Parse(); err != nil || server != m.br.Matrix.ServerName() || m.br.IsGhostMXID(member) { writeError(w, http.StatusBadRequest, "M_INVALID_PARAM", "Members must be users of this homeserver") return } } ctx, timer := steptimer.Start(m.requestContext(r)) waiting := time.Now() lock := m.roomLock(oldRoom) lock.Lock() defer lock.Unlock() t := moveTimings{Lock: time.Since(waiting).Milliseconds()} tookLong(ctx, "move_room_lock", waiting) moving := time.Now() newRoom, created, err := m.move(ctx, userID, oldRoom, req) t.Move = time.Since(moving).Milliseconds() t.Steps = timer.Steps() if time.Duration(t.Move)*time.Millisecond >= slowStep { zerolog.Ctx(ctx).Warn().Bool("created", created).Interface("timings", t).Msg("A room move took long") } if err != nil { answerError(ctx, w, err, "Failed to move the room") return } writeJSON(w, http.StatusOK, map[string]any{"newRoomId": newRoom, "created": created, "timings": t}) } // moveTimings is where a move's time went: waiting for the room's lock, the move, and the steps // bridgekit marks within it (making the room, inviting, the ghosts' joins and profiles). Only step // names, counts and milliseconds: the move's log and answer carry it. type moveTimings struct { Lock int64 `json:"lockMs"` Move int64 `json:"moveMs"` Steps map[string]steptimer.Span `json:"steps"` } func (m *mover) move(ctx context.Context, userID id.UserID, oldRoom id.RoomID, req moveRequest) (id.RoomID, bool, error) { // Whether the history is being written, asked before the row is read: a job that ends after this // has saved all it writes (run), and none starts while the room's lock is held (handleMigrate), // so a row read once none runs stays as read. running := m.running(oldRoom) existing, err := m.store.room(ctx, oldRoom) if err != nil { return "", false, err } if existing != nil && !existing.owns(userID) { return "", false, failWith(http.StatusForbidden, "M_FORBIDDEN", "The room was moved for another user") } if existing != nil && existing.State != stateMoving { if existing.NewRoom == "" || existing.Error == errNotEncrypted { return "", false, failWith(http.StatusConflict, "XSG_NOT_ENCRYPTED", "The room's new room is not encrypted") } // While the history is being written the move stays as it is: the job saves the whole row as // it goes, so a row saved here meanwhile would be written over, or would write over how far // the job got (its attempt, after which an event cut short would be sent again). if running { return existing.NewRoom, false, nil } if existing.Kind == kindPortal { if err = m.retakePortalMembers(ctx, existing, req.Members); err != nil { return "", false, err } } else if err = m.retakeXessengerRoom(ctx, userID, existing, req.Members); err != nil { return "", false, err } return existing.NewRoom, false, nil } if existing != nil { // A move cut short goes on with the members of this call: who reads the room may have changed // since it began, and finishPortalMove invites them into the room it makes. if err = m.takeMembers(ctx, existing, req.Members); err != nil { return "", false, err } return m.finishPortalMove(ctx, existing) } portal, err := m.br.GetPortalByMXID(ctx, oldRoom) if err != nil { return "", false, err } if portal != nil { return m.movePortal(ctx, userID, oldRoom, portal, req.Members) } if req.NewRoomID != "" { newRoom, err := m.adoptXessengerRoom(ctx, userID, oldRoom, req) return newRoom, false, err } return "", false, failWith(http.StatusNotFound, "M_NOT_FOUND", "The room is no portal of this bridge and was not moved") } // movePortal moves a portal into a new room: bridgev2 forgets the old room and creates the portal's // room again, which bridgekit makes encrypted because its user is switched on. Remote events that // arrive in between create the room themselves (and are bridged into it); the few that cannot // create a room (an edit, a reaction) are dropped as for any portal without a room. func (m *mover) movePortal(ctx context.Context, userID id.UserID, oldRoom id.RoomID, portal *bridgev2.Portal, members []id.UserID) (id.RoomID, bool, error) { login, err := m.portalLogin(ctx, portal) if err != nil { return "", false, err } if login.UserMXID != userID { return "", false, failWith(http.StatusForbidden, "M_FORBIDDEN", "The room is another user's portal") } if !m.kit.E2EEEnabled(ctx, userID) { return "", false, failWith(http.StatusConflict, "XSG_NOT_ENABLED", "The user is not switched on in this bridge") } if _, err = m.sealer(); err != nil { return "", false, failWith(http.StatusServiceUnavailable, "XSG_UNAVAILABLE", "The bridge cannot seal what a move keeps") } // The chat's info is read first: without the network the old room is not let go. info, err := m.moveChatInfo(ctx, login, portal, oldRoom) if err != nil { return "", false, err } row := &room{ OldRoom: oldRoom, User: userID, Kind: kindPortal, PortalID: portal.ID, PortalReceiver: portal.Receiver, Members: othersThan(userID, members), State: stateMoving, } if err = m.store.putRoom(ctx, row); err != nil { return "", false, err } if err = m.letGo(ctx, oldRoom, portal, login, info); err != nil { return "", false, err } return m.finishPortalMove(ctx, row) } // letGo has the portal let go of its old room and bridgev2 create its room again, which bridgekit // makes encrypted. func (m *mover) letGo(ctx context.Context, oldRoom id.RoomID, portal *bridgev2.Portal, login *bridgev2.UserLogin, info *bridgev2.ChatInfo) error { if err := portal.RemoveMXID(ctx); err != nil { return fmt.Errorf("failed to let the portal go of its room: %w", err) } return m.createRoom(ctx, oldRoom, portal, login, info) } // createRoom has bridgev2 create the portal's room again with the info moveChatInfo gave, which carries // no backfill. The portal's backfill task from its old room goes first: the queue would write older // history into the new room unmarked, as forward backfill would (moveChatInfo). func (m *mover) createRoom(ctx context.Context, oldRoom id.RoomID, portal *bridgev2.Portal, login *bridgev2.UserLogin, info *bridgev2.ChatInfo) error { if err := m.br.DB.BackfillTask.Delete(ctx, portal.PortalKey); err != nil { return fmt.Errorf("failed to drop the moved portal's backfill task: %w", err) } if err := portal.CreateMatrixRoom(ctx, login, info); err != nil { zerolog.Ctx(ctx).Err(err).Stringer("room_id", oldRoom).Msg("Failed to create the new room of a moved portal") return failWith(http.StatusBadGateway, "XSG_NETWORK", "The new room could not be created yet") } return nil } // resumePortalMove lets go of the old room for a move that stopped before the portal did, on // movePortal's conditions: the user still switched on, and the messenger answering. func (m *mover) resumePortalMove(ctx context.Context, row *room, portal *bridgev2.Portal) error { login, err := m.portalLogin(ctx, portal) if err != nil { return err } if !m.kit.E2EEEnabled(ctx, row.User) { return failWith(http.StatusConflict, "XSG_NOT_ENABLED", "The user is not switched on in this bridge") } info, err := m.moveChatInfo(ctx, login, portal, row.OldRoom) if err != nil { return err } return m.letGo(ctx, row.OldRoom, portal, login, info) } // finishPortalMove records the room the portal now has. It also finishes a move the bridge stopped // in the middle of: the portal is found by its key. func (m *mover) finishPortalMove(ctx context.Context, row *room) (id.RoomID, bool, error) { portal, err := m.br.GetExistingPortalByKey(ctx, networkid.PortalKey{ID: row.PortalID, Receiver: row.PortalReceiver}) if err != nil { return "", false, err } else if portal == nil { return "", false, failWith(http.StatusNotFound, "M_NOT_FOUND", "The moved portal no longer exists") } if portal.MXID == row.OldRoom { // The bridge stopped, or letting go failed, before the portal let go of its old room: let go // now, as movePortal would have. if err = m.resumePortalMove(ctx, row, portal); err != nil { return "", false, err } } else if portal.MXID == "" { // Let go of, but not made again (creating it failed, or the bridge stopped in between): made now, // with the info movePortal would have given. The old room is still there to read. login, err := m.portalLogin(ctx, portal) if err != nil { return "", false, err } info, err := m.moveChatInfo(ctx, login, portal, row.OldRoom) if err != nil { return "", false, err } if err = m.createRoom(ctx, row.OldRoom, portal, login, info); err != nil { return "", false, err } } newRoom := portal.MXID if newRoom == "" || newRoom == row.OldRoom { return "", false, errors.New("the portal has no new room") } encrypted, err := m.encrypted(ctx, newRoom) if err != nil { return "", false, err } else if !encrypted { // A person has to look at it: the portal now lives in a room the history must not go to. row.NewRoom, row.State, row.Error = newRoom, stateFailed, errNotEncrypted if err = m.store.putRoom(ctx, row); err != nil { return "", false, err } return "", false, failWith(http.StatusConflict, "XSG_NOT_ENCRYPTED", "The new room is not encrypted") } present, err := m.sealPresentGhosts(ctx, row.OldRoom, newRoom) if err != nil { return "", false, err } // The move is finished only with its user in the new room: bridgev2 brings them in as it makes the // room, and stops where the call making it was cut short (user.go). if err = m.ensureUser(ctx, newRoom, row.User); err != nil { return "", false, err } row.NewRoom, row.SealedPresent, row.State = newRoom, present, stateMoved if err = m.store.putRoom(ctx, row); err != nil { return "", false, err } if err = m.invite(ctx, newRoom, row.Members, row); err != nil { return "", false, err } zerolog.Ctx(ctx).Info().Stringer("old_room_id", row.OldRoom).Stringer("new_room_id", newRoom).Msg("Moved portal to an encrypted room") m.fillNameAfterMove(ctx, row) return newRoom, true, nil } func (m *mover) portalLogin(ctx context.Context, portal *bridgev2.Portal) (*bridgev2.UserLogin, error) { if portal.Receiver == "" { return nil, failWith(http.StatusConflict, "XSG_NOT_SPLIT", "The portal belongs to no single login") } login := m.br.GetCachedUserLoginByID(portal.Receiver) if login == nil { var err error if login, err = m.br.GetExistingUserLoginByID(ctx, portal.Receiver); err != nil { return nil, err } } if login == nil || login.Client == nil || !login.Client.IsLoggedIn() { return nil, failWith(http.StatusBadGateway, "XSG_NETWORK", "The portal's login is not connected") } return login, nil } // invite brings the identities sharing the connection into the new room, and remembers them. func (m *mover) invite(ctx context.Context, newRoom id.RoomID, members []id.UserID, row *room) error { changed := false for _, member := range members { if member == row.User { continue } if err := m.br.Bot.EnsureInvited(ctx, newRoom, member); err != nil { return fmt.Errorf("failed to invite %s: %w", member, err) } if !slices.Contains(row.Members, member) { row.Members = append(row.Members, member) changed = true } } if changed { return m.store.putRoom(ctx, row) } return nil } // adoptXessengerRoom takes on two Xessenger users' room, whose new room the API made: the bot // joins it to write the history, as its users, and leaves when release is called. The members are // the users still in the old room (one of them may have left it, or never accepted the request). func (m *mover) adoptXessengerRoom(ctx context.Context, userID id.UserID, oldRoom id.RoomID, req moveRequest) (id.RoomID, error) { if !slices.Contains(req.Members, userID) { return "", failWith(http.StatusBadRequest, "M_INVALID_PARAM", "A Xessenger room's members must include the user") } if !strings.HasPrefix(string(req.NewRoomID), "!") || req.NewRoomID == oldRoom { return "", failWith(http.StatusBadRequest, "M_INVALID_PARAM", "Not a new room ID") } if _, err := m.sealer(); err != nil { return "", failWith(http.StatusServiceUnavailable, "XSG_UNAVAILABLE", "The bridge cannot seal what a move keeps") } if err := m.br.Bot.EnsureJoined(ctx, req.NewRoomID); err != nil { zerolog.Ctx(ctx).Err(err).Stringer("room_id", req.NewRoomID).Msg("Failed to join a Xessenger room's new room") return "", failWith(http.StatusConflict, "XSG_NOT_INVITED", "The bot could not join the new room") } // Reading the state also tells the bridge's state store who is in the room and that it is // encrypted, which encrypting for its members needs. if _, err := m.conn.Bot.State(ctx, req.NewRoomID); err != nil { return "", fmt.Errorf("failed to read the new room's state: %w", err) } if encrypted, err := m.encrypted(ctx, req.NewRoomID); err != nil { return "", err } else if !encrypted { return "", failWith(http.StatusConflict, "XSG_NOT_ENCRYPTED", "The new room is not encrypted") } joined, err := m.conn.Bot.JoinedMembers(ctx, req.NewRoomID) if err != nil { return "", fmt.Errorf("failed to read the new room's members: %w", err) } for _, member := range req.Members { if _, ok := joined.Joined[member]; !ok { return "", failWith(http.StatusConflict, "XSG_MEMBERS_NOT_JOINED", "Not every member has joined the new room") } } reader, err := m.doublePuppet(ctx, userID) if err != nil { return "", err } old, err := reader.JoinedMembers(ctx, oldRoom) if err != nil { return "", failWith(http.StatusNotFound, "M_NOT_FOUND", "The user is not in the old room") } for member := range old.Joined { if !slices.Contains(req.Members, member) { return "", failWith(http.StatusConflict, "XSG_NOT_XESSENGER_ROOM", "The old room has others than the given members") } } row := &room{OldRoom: oldRoom, NewRoom: req.NewRoomID, User: userID, Kind: kindXessenger, Members: req.Members, State: stateMoved} if err = m.store.putRoom(ctx, row); err != nil { return "", err } zerolog.Ctx(ctx).Info().Stringer("old_room_id", oldRoom).Stringer("new_room_id", req.NewRoomID).Msg("Took on a Xessenger room's move") return req.NewRoomID, nil } // retakePortalMembers takes the members of a portal's move called again, which the API gives before // it starts or retries writing the history: one it no longer gives let go of the connection, and the // bridge's member sync puts them out of the new room (bridgekit members.go), which the history waits // for (membersJoined). One it gives is invited, as the first move does. Once the history moved the // members stay: from then on who is in the room is the member sync's alone. The user is brought in // whatever the state, a move from before that left them out among them (user.go): a history written // before they came in is found by the next migrate call all the same, which reads when they did. func (m *mover) retakePortalMembers(ctx context.Context, existing *room, members []id.UserID) error { if err := m.ensureUser(ctx, existing.NewRoom, existing.User); err != nil { return err } if members == nil || existing.State == stateDone { return nil } for _, member := range othersThan(existing.User, members) { if err := m.br.Bot.EnsureInvited(ctx, existing.NewRoom, member); err != nil { return fmt.Errorf("failed to invite %s: %w", member, err) } } return m.takeMembers(ctx, existing, members) } // takeMembers keeps the members a call gives for a portal's move. A call without members (an API from // before them) changes nothing. func (m *mover) takeMembers(ctx context.Context, existing *room, members []id.UserID) error { if members == nil { return nil } given := othersThan(existing.User, members) if slices.Equal(slices.Sorted(slices.Values(existing.Members)), slices.Sorted(slices.Values(given))) { return nil } existing.Members = given return m.store.putRoom(ctx, existing) } // othersThan is a portal's members as a move keeps them: the identities sharing the connection other // than the user it was moved for, once each. func othersThan(user id.UserID, members []id.UserID) []id.UserID { var others []id.UserID for _, member := range members { if member != user && !slices.Contains(others, member) { others = append(others, member) } } return others } // running reports whether the room's history is being written now, by a job of this process. func (m *mover) running(roomID id.RoomID) bool { m.jobLock.Lock() defer m.jobLock.Unlock() j := m.jobs[roomID] return j != nil && j.state == stateRunning } // retakeXessengerRoom takes the members of a Xessenger room's move called again before its history // moves (a move cut short, gone on with): one who took up the request since is in the old room now, // and the history writes their messages too (writer.intent). Once it moves, the members stay. func (m *mover) retakeXessengerRoom(ctx context.Context, userID id.UserID, existing *room, members []id.UserID) error { if existing.State != stateMoved || slices.Equal(slices.Sorted(slices.Values(existing.Members)), slices.Sorted(slices.Values(members))) { return nil } if !slices.Contains(members, userID) { return failWith(http.StatusBadRequest, "M_INVALID_PARAM", "A Xessenger room's members must include the user") } existing.Members = members return m.store.putRoom(ctx, existing) } // encrypted asks the server, not only the state store: writing history into a room that is not // encrypted could not be taken back. func (m *mover) encrypted(ctx context.Context, roomID id.RoomID) (bool, error) { var content event.EncryptionEventContent err := m.conn.Bot.StateEvent(ctx, roomID, event.StateEncryption, "", &content) return encryptionOf(&content, err) } // encryptionOf reads the server's answer: a room with no encryption event is not encrypted, while a // server that did not answer says nothing about the room (the error goes back, and a later try asks // again). func encryptionOf(content *event.EncryptionEventContent, err error) (bool, error) { if isNotFound(err) { return false, nil } else if err != nil { return false, fmt.Errorf("failed to read the room's encryption: %w", err) } return content.Algorithm == id.AlgorithmMegolmV1, nil } // sealPresentGhosts remembers, sealed, which ghosts are in the new room when it is made: the ghosts // that join only to write their old messages leave again afterwards. func (m *mover) sealPresentGhosts(ctx context.Context, oldRoom, newRoom id.RoomID) (string, error) { members, err := m.br.Matrix.GetMembers(ctx, newRoom) if err != nil { return "", fmt.Errorf("failed to read the new room's members: %w", err) } var ghosts []id.UserID for userID := range members { if m.br.IsGhostMXID(userID) { ghosts = append(ghosts, userID) } } slices.Sort(ghosts) data, err := json.Marshal(nonNil(ghosts)) if err != nil { return "", err } sealer, err := m.sealer() if err != nil { return "", err } return sealer.Seal(m.sealContext("xessenger/migrate/present/v1", oldRoom, ""), data) } func (m *mover) openPresentGhosts(row *room) (map[id.UserID]bool, error) { present := map[id.UserID]bool{} if row.SealedPresent == "" { return present, nil } sealer, err := m.sealer() if err != nil { return nil, err } data, err := sealer.Open(m.sealContext("xessenger/migrate/present/v1", row.OldRoom, ""), row.SealedPresent) if err != nil { return nil, err } var ghosts []id.UserID if err = json.Unmarshal(data, &ghosts); err != nil { return nil, err } for _, ghost := range ghosts { present[ghost] = true } return present, nil }