package migrate import ( "context" "encoding/json" "errors" "io" "net/http" "sync" "sync/atomic" "time" "github.com/rs/zerolog" "maunium.net/go/mautrix/bridgev2" "maunium.net/go/mautrix/bridgev2/matrix" "maunium.net/go/mautrix/id" "xessenger/bridgekit/internal/storeseal" ) // The extension API the API server calls with the bridge's provisioning secret (bridgekit checks it // before a request gets here). Every path starts with /_xessenger/v1/e2ee/users/{mxid}: // // POST …/rooms/{roomId}/move {members?, newRoomId?} -> {newRoomId, created, timings?} // POST …/rooms/{roomId}/migrate {retry?, start?} -> {state, done, total, canAsk, phase?, elapsedMs?, error?, result?, timings?} // GET …/rooms/{roomId}/migrate/media?after=&limit= -> {media: [{mxc, sha256}], next} // POST …/rooms/{roomId}/migrate/map {eventIds?, before?} -> {map, floor?} // POST …/rooms/{roomId}/migrate/redacted {eventIds} -> {events, files, digest, redacted} // POST …/rooms/{roomId}/migrate/strays {apply?} -> {newRoomId, strays, redacted, unreadable} // POST …/rooms/{roomId}/release -> {left} // POST …/management-room/forget {roomId} -> {forgotten} // // {roomId} is always the old (plaintext) room. One more path forgets old ghosts once the API has // deleted their accounts: POST /_xessenger/v1/e2ee/ghosts/forget {ghostIds} -> {forgotten}. const prefix = "/_xessenger/v1/e2ee/users/{mxid}" // kit is what bridgekit's Matrix connector gives an extension. type kit interface { Unwrap() *matrix.Connector E2EEEnabled(ctx context.Context, userID id.UserID) bool HomeserverPerson(userID id.UserID) bool StoreSealer() *storeseal.Sealer } // fileNoter is how bridgekit's connector keeps the files of an event a move wrote, or found written // (findWritten), to write down at the API (docs/e2ee/work-plan.md 4.12), with the attachments of a // mail, read from its mail.json then: the copies the move made are let go of when it is done // (fileHolder). bridgekit's intents keep them as the event goes out as well, without telling the move // whether they could. type fileNoter interface { NoteWrittenFiles(ctx context.Context, roomID id.RoomID, eventID id.EventID, content json.RawMessage, sent time.Time) error } // fileHolder is how bridgekit's connector holds the copies a move made in the new room until the move // is done (docs/e2ee/work-plan.md 4.12): a copy goes into every message that carries its file, and a // message moved earlier may be deleted on the messenger before the later ones are written, which would // take the copy with it. type fileHolder interface { HoldMovedFiles(ctx context.Context, roomID, oldRoom id.RoomID, files []id.ContentURIString) error ReleaseMovedFiles(ctx context.Context, roomID, oldRoom id.RoomID) error } // EncryptionWaiter is how bridgekit's connector runs a pass once the bridge's encryption runs // (WhenEncrypting): the names of moved groups go into their rooms' encrypted metadata (fillMovedNames). // Exported so that bridgekit's tests hold its connector to it: a connector without it would leave the // names unfilled with only a warning at the start. type EncryptionWaiter interface { WhenEncrypting(fn func(ctx context.Context)) } // RoomMetaSender is how bridgekit's connector sends an encrypted room's metadata as its portal has it // now (SendRoomMeta), and reports whether it went (false: it went before as it is now). A room that // cannot take it now (not encrypted, or its owner away) is an error; one held as its owner is out of it // carries RoomMetaOwnerAway (ownerAway). Exported for bridgekit's tests, as EncryptionWaiter is. type RoomMetaSender interface { SendRoomMeta(ctx context.Context, roomID id.RoomID) (bool, error) } // ownerAway reports whether err is bridgekit's room metadata held as the room's owner is out of it, as // the homeserver has it too, or as the room has no owner switched on (RoomMetaOwnerAway): the room does // not take its metadata until the owner is back, if ever. func ownerAway(err error) bool { var held interface{ RoomMetaOwnerAway() bool } return errors.As(err, &held) && held.RoomMetaOwnerAway() } type mover struct { br *bridgev2.Bridge kit kit conn *matrix.Connector store *store log zerolog.Logger // ready is false when the bridge runs without bridgekit or the tables could not be made: every // route then answers 503. ready bool jobLock sync.Mutex jobs map[id.RoomID]*job // roomLocks serialise moves, history runs' starts, releases, deleted-event marks (handleRedacted) // and stray redactions (handleStrays) of one old room. Taken before jobLock, never after it. roomLocks sync.Map // joinUser stands in for joining a room as a user through their double puppet (joinAsUser) in tests. joinUser func(ctx context.Context, roomID id.RoomID, userID id.UserID) error // namesFilled is set once the moved groups' names are being filled in (fillMovedNames). namesFilled atomic.Bool } // Install is a bridgekit.Extension: bridgekit.Install(&m, bridgekit.Options{Extensions: // []bridgekit.Extension{migrate.Install}}). func Install(br *bridgev2.Bridge, router *http.ServeMux) { m := &mover{br: br, log: br.Log.With().Str("component", "xessenger-migrate").Logger(), jobs: map[id.RoomID]*job{}} m.ready = m.setup() if m.ready { if _, ok := m.kit.(RoomMetaSender); !ok { m.log.Warn().Msg("The bridge cannot send a room's metadata; moved groups' names are not filled in") } if waiter, ok := m.kit.(EncryptionWaiter); ok { waiter.WhenEncrypting(func(ctx context.Context) { m.fillMovedNames(m.log.WithContext(ctx)) }) } else { m.log.Warn().Msg("The bridge cannot run a pass once its encryption runs; moved groups' names are not filled in at the start") } } router.HandleFunc("POST "+prefix+"/rooms/{roomId}/move", m.guard(m.handleMove)) router.HandleFunc("POST "+prefix+"/rooms/{roomId}/migrate", m.guard(m.handleMigrate)) router.HandleFunc("GET "+prefix+"/rooms/{roomId}/migrate/media", m.guard(m.handleMedia)) router.HandleFunc("POST "+prefix+"/rooms/{roomId}/migrate/map", m.guard(m.handleMap)) router.HandleFunc("POST "+prefix+"/rooms/{roomId}/migrate/redacted", m.guard(m.handleRedacted)) router.HandleFunc("POST "+prefix+"/rooms/{roomId}/migrate/strays", m.guard(m.handleStrays)) router.HandleFunc("POST "+prefix+"/rooms/{roomId}/release", m.guard(m.handleRelease)) router.HandleFunc("POST "+prefix+"/management-room/forget", m.guard(m.handleForget)) router.HandleFunc("POST /_xessenger/v1/e2ee/ghosts/forget", m.guard(m.handleForgetGhosts)) } func (m *mover) setup() bool { k, ok := m.br.Matrix.(kit) if !ok { m.log.Warn().Msg("The bridge runs without bridgekit; history moves are off") return false } m.kit, m.conn = k, k.Unwrap() m.store = newStore(m.br.DB.Database, m.br.ID, m.log) if err := m.store.upgrade(m.log.WithContext(context.Background())); err != nil { m.log.Err(err).Msg("Failed to upgrade the history move tables; history moves are off") return false } return true } func (m *mover) guard(next http.HandlerFunc) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { if !m.ready { writeError(w, http.StatusServiceUnavailable, "XSG_UNAVAILABLE", "History moves are off in this bridge") return } next(w, r) } } func (m *mover) requestContext(r *http.Request) context.Context { return m.log.With().Str("api", r.URL.Path).Logger().WithContext(r.Context()) } // backgroundContext outlives the request that starts a migration. func (m *mover) backgroundContext() context.Context { if m.br.BackgroundCtx != nil { return m.log.WithContext(m.br.BackgroundCtx) } return m.log.WithContext(context.Background()) } func (m *mover) roomLock(roomID id.RoomID) *sync.Mutex { lock, _ := m.roomLocks.LoadOrStore(roomID, &sync.Mutex{}) return lock.(*sync.Mutex) } // sealContext names a sealed value as bridgekit's store does: its kind, the bridge, the old room and // the rest of its row's key, so a value moved to another row, room or bridge database does not open. func (m *mover) sealContext(kind string, oldRoom id.RoomID, key string) string { return kind + "\x00" + string(m.br.ID) + "\x00" + string(oldRoom) + "\x00" + key } // sealer seals what a move keeps that touches content: the keys of the copied files, the content // hashes of the moved events, and which ghosts were in the old room. Every value names its kind in // its additional data (xessenger/migrate/…). func (m *mover) sealer() (*storeseal.Sealer, error) { sealer := m.kit.StoreSealer() if !sealer.Ready() { return nil, storeseal.ErrNoKey } return sealer, nil } // pathUser is a user of this homeserver who is no ghost and not the bot. func (m *mover) pathUser(w http.ResponseWriter, r *http.Request) (id.UserID, bool) { userID := id.UserID(r.PathValue("mxid")) _, server, err := userID.Parse() if err != nil || server != m.br.Matrix.ServerName() || userID == m.br.Bot.GetMXID() || m.br.IsGhostMXID(userID) { writeError(w, http.StatusBadRequest, "M_INVALID_PARAM", "Not a user of this homeserver") return "", false } return userID, true } func pathRoom(w http.ResponseWriter, r *http.Request) (id.RoomID, bool) { roomID := id.RoomID(r.PathValue("roomId")) if len(roomID) < 3 || roomID[0] != '!' { writeError(w, http.StatusBadRequest, "M_INVALID_PARAM", "Not a room ID") return "", false } return roomID, true } // owns reports whether the user is the one a move belongs to, or one of the identities it brought. func (r *room) owns(userID id.UserID) bool { if r.User == userID { return true } for _, member := range r.Members { if member == userID { return true } } return false } // readBody decodes a request body of at most 256 KiB; an empty body is an empty object. func readBody(w http.ResponseWriter, r *http.Request, value any) bool { err := json.NewDecoder(io.LimitReader(r.Body, 256<<10)).Decode(value) if err != nil && !errors.Is(err, io.EOF) { writeError(w, http.StatusBadRequest, "M_NOT_JSON", "Invalid request body") return false } return true } func writeJSON(w http.ResponseWriter, status int, value any) { w.Header().Set("Content-Type", "application/json") w.WriteHeader(status) _ = json.NewEncoder(w).Encode(value) } func writeError(w http.ResponseWriter, status int, errcode, message string) { writeJSON(w, status, map[string]string{"errcode": errcode, "error": message}) } // apiError is an answer a handler gives up with. type apiError struct { status int errcode string message string } func (e *apiError) Error() string { return e.errcode + ": " + e.message } func failWith(status int, errcode, message string) *apiError { return &apiError{status: status, errcode: errcode, message: message} } // answerError writes an apiError as it is and anything else as a 500, logged. func answerError(ctx context.Context, w http.ResponseWriter, err error, what string) { var known *apiError if errors.As(err, &known) { writeError(w, known.status, known.errcode, known.message) return } zerolog.Ctx(ctx).Err(err).Msg(what) writeError(w, http.StatusInternalServerError, "M_UNKNOWN", what) }