// 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 ( "context" "database/sql" "encoding/json" "errors" "fmt" "slices" "sync" "time" "github.com/rs/zerolog" "go.mau.fi/util/dbutil" "maunium.net/go/mautrix/bridgev2/networkid" "maunium.net/go/mautrix/crypto" "maunium.net/go/mautrix/event" "maunium.net/go/mautrix/id" ) // An identity who reads one of a switched-on user's encrypted rooms from some time on has none of the // keys of what came before (docs/e2ee/work-plan.md 4.2 ⑩): a member invited into a room that was there // already, such as the identity of a workspace that links the connection late (the API's late link, work // plan 3), or a member invited before this bridge switched them on, whose devices it trusts only then // (members.go). The room's history is shared (bridgev2 makes rooms with private_chat), so their app // pages back through it, and the bridge hands them the keys to read it: every session of the room it // has, its own from their first index (delete_keys is off) and the app devices' from where it got them, // as an MSC4268 room key bundle. The app's Rust crypto drops a forwarded room key it did not ask for, // and only a session's creator may send it as m.room_key, so this is the way its keys reach a reader // who came later. // // The bundle goes up as an encrypted file, written down for deletion under the room before its key goes // (mediarefs.go), and its key goes over Olm to each device of the identity's that this bridge trusts, as // room keys go (trust.go), in an io.element.msc4268.room_key_bundle {room_id, file}: mautrix puts the bot // device's keys in it (sender_device_keys), without which the app's Rust crypto drops it. The app takes a // bundle only from a bridge bot device it pinned (engine/history.ts). The room's outbound session was // dropped by then (mautrix on the invite, resendMeta, OnDevicesChanged), so what follows reaches the // identity's devices as any room key does, and a session of the bundle opens what it carried on with // (Megolm only ratchets forward). // // The room and identity are noted (08-history.sql) as a member sync invites a member into a room, // before the invite (syncRoomMembersLocked), and before the bridge comes to trust the devices of a // member in rooms already (noteHistoryOf, from enable and checkTrust): while the bridge database takes // no note, their devices stay untrusted for the next trust check to note again. The bundles go in the // background (queueHistory) once the devices are trusted (resendMetaTo), and what is left goes again // when encryption starts and every trust interval (watchTrust). An identity who no longer reads the room (the room's login no longer // has them, they are not in it, or its owner left it) has its row forgotten, and so does a holder, whose // devices are never trusted; one with no device this bridge trusts yet (not switched on here) keeps it. // Who reads the room is looked at again right before the key goes, as a link let go meanwhile changes // it at once (handleMembers). The room's member lock is held meanwhile: nobody is put out of the room, // nor its session dropped, while its keys go out. // eventRoomKeyBundle is MSC4268's room key bundle, under the unstable type the app's Rust crypto takes. var eventRoomKeyBundle = event.Type{Type: "io.element.msc4268.room_key_bundle", Class: event.ToDeviceEventType} // historyKeysEvent is the event a room key bundle's file is written down under, in its room // (sendRoomHistory). No Matrix event takes this ID; the API takes it as any other. func historyKeysEvent(mediaID string) id.EventID { return id.EventID("$xessenger-keys:" + mediaID) } // roomKeyBundle is what a room key bundle's file holds: the room's sessions, and those withheld (none). // The app's Rust crypto needs both lists, empty or not. type roomKeyBundle struct { RoomKeys []historyKey `json:"room_keys"` Withheld []any `json:"withheld"` } // historyKey is one session of a room key bundle, as a key export has it without the forwarding chain. type historyKey struct { Algorithm id.Algorithm `json:"algorithm"` RoomID id.RoomID `json:"room_id"` SenderKey id.SenderKey `json:"sender_key"` SessionID id.SessionID `json:"session_id"` SessionKey string `json:"session_key"` SenderClaimedKeys crypto.SenderClaimedKeys `json:"sender_claimed_keys"` } // historySend is the background send of the room key bundles due (queueHistory). type historySend struct { mu sync.Mutex running bool again bool } // noteHistory notes that a room's keys go to the user (08-history.sql); queueHistory sends them. func (k *Kit) noteHistory(ctx context.Context, roomID id.RoomID, userID id.UserID) error { if err := k.store.putHistoryDue(ctx, roomID, userID); err != nil { return fmt.Errorf("failed to note that the keys of %s go to %s: %w", roomID, userID, err) } return nil } // noteHistoryOf notes the rooms of other users' that the user is in already, for their keys to go to // the user once the bridge trusts the user's devices (resendMetaTo queues them). It comes before the // trust is set (api.go enable, checkTrust), which waits while a note fails: nothing else notes a room // the user is in already, and the trust check goes on until the trust is set, the bridge stopped or not. func (k *Kit) noteHistoryOf(ctx context.Context, userID id.UserID) error { if k.conn == nil || k.conn.StateStore == nil || k.br == nil { return nil } rooms, err := k.conn.StateStore.FindSharedRooms(ctx, userID) if err != nil { return fmt.Errorf("failed to find the rooms of others %s is in: %w", userID, err) } for _, roomID := range rooms { if k.inOthersRoom(ctx, roomID, userID) { if err = k.noteHistory(ctx, roomID, userID); err != nil { return err } } } return nil } // inOthersRoom reports whether the user is in a room of another user's, as their member is. func (k *Kit) inOthersRoom(ctx context.Context, roomID id.RoomID, userID id.UserID) bool { owner := k.roomOwner(ctx, roomID) return owner != "" && owner != userID && k.conn.StateStore.IsMembership(ctx, roomID, userID, event.MembershipJoin, event.MembershipInvite) } // queueHistory sends the room key bundles due in the background: now, and once more when a send is // going on already, so that what was noted meanwhile goes too. What fails goes again every trust // interval (watchTrust). func (k *Kit) queueHistory() { k.history.mu.Lock() defer k.history.mu.Unlock() if k.history.running { k.history.again = true return } k.history.running = true go func() { ctx := k.backgroundContext() for { if err := k.sendHistory(ctx); err != nil { zerolog.Ctx(ctx).Err(err).Msg("Failed to send the keys of rooms to the identities who read them late") } k.history.mu.Lock() if !k.history.again { k.history.running = false k.history.mu.Unlock() return } k.history.again = false k.history.mu.Unlock() } }() } // sendHistory sends the room key bundles due, a room at a time. func (k *Kit) sendHistory(ctx context.Context) error { dues, err := k.store.historyDues(ctx) if err != nil { return fmt.Errorf("failed to read the rooms whose keys are due: %w", err) } var errs []error for start := 0; start < len(dues); { end := start + 1 for end < len(dues) && dues[end].RoomID == dues[start].RoomID { end++ } if err = k.sendRoomHistory(ctx, dues[start].RoomID, dues[start:end]); err != nil { errs = append(errs, err) } start = end } return errors.Join(errs...) } // historyReading is whether a row's identity reads the room still (historyReaders), and has a device this // bridge trusts to send its keys to. type historyReading int const ( // historyGone: they no longer read the room, and the row is forgotten. historyGone historyReading = iota // historyWaits: they read it, but this bridge trusts no device of theirs yet, and the row stays. historyWaits // historyGoes: the keys go to their trusted devices. historyGoes ) // sendRoomHistory sends a room's key bundle to the identities it is due to who still read the room and // have a device this bridge trusts, with the room's member lock held. Who reads it is looked at again // once the bundle's file is up, right before its key goes: a link let go meanwhile (handleMembers) // changes the members at once. A row is forgotten once its bundle went to every such device (a device // gone meanwhile counts as reached), or once its identity no longer reads the room; it stays otherwise, // for the next send. func (k *Kit) sendRoomHistory(ctx context.Context, roomID id.RoomID, dues []historyDue) error { mach := k.machine() if mach == nil { return errNoCrypto } c := machineCrypto{mach: mach} lock := k.memberLock(roomID) lock.Lock() defer lock.Unlock() owner, members, err := k.historyReaders(ctx, roomID) if err != nil { return err } var errs []error var readers []historyDue for _, due := range dues { reading, _, err := k.historyReading(ctx, c, roomID, owner, members, due.UserID) switch { case err != nil: errs = append(errs, err) case reading == historyGone: errs = append(errs, k.forgetHistory(ctx, due)) case reading == historyGoes: readers = append(readers, due) } } if len(readers) == 0 { return errors.Join(errs...) } bundle, err := k.historyBundle(ctx, mach, roomID) if err != nil { return errors.Join(append(errs, fmt.Errorf("failed to read the sessions of %s: %w", roomID, err))...) } else if len(bundle.RoomKeys) == 0 { // Nothing was encrypted in the room before them. for _, reader := range readers { errs = append(errs, k.forgetHistory(ctx, reader)) } return errors.Join(errs...) } file, err := k.historyFile(ctx, roomID, bundle) if err != nil { return errors.Join(append(errs, err)...) } content := &event.RoomKeyBundleEventContent{RoomID: roomID, File: *file} for _, reader := range readers { owner, members, err = k.historyReaders(ctx, roomID) if err != nil { return errors.Join(append(errs, err)...) } reading, devices, err := k.historyReading(ctx, c, roomID, owner, members, reader.UserID) if err != nil { errs = append(errs, err) continue } else if reading == historyGone { errs = append(errs, k.forgetHistory(ctx, reader)) continue } else if reading == historyWaits { continue } reached := true for deviceID, signingKey := range devices { err = c.SendToDevice(ctx, reader.UserID, deviceID, signingKey, eventRoomKeyBundle, content) if err != nil && !errors.Is(err, errDeviceGone) { errs = append(errs, fmt.Errorf("failed to send the keys of %s to %s of %s: %w", roomID, deviceID, reader.UserID, err)) reached = false } } if reached { zerolog.Ctx(ctx).Debug(). Stringer("room_id", roomID). Stringer("user_id", reader.UserID). Int("sessions", len(bundle.RoomKeys)). Int("devices", len(devices)). Msg("Sent the room's keys to an identity who reads it late") errs = append(errs, k.forgetHistory(ctx, reader)) } } return errors.Join(errs...) } // historyReading tells whether the user reads the room as one of its owner's members, as historyReaders // gave them (not its owner, in the room or invited, not a holder), with the devices of theirs this bridge // trusts. One not switched on here waits: their switch-on pins whose devices the keys go to. func (k *Kit) historyReading(ctx context.Context, c identityCrypto, roomID id.RoomID, owner id.UserID, members []id.UserID, userID id.UserID) (historyReading, map[id.DeviceID]id.Ed25519, error) { user := k.user(userID) if userID == owner || !slices.Contains(members, userID) || !k.conn.StateStore.IsMembership(ctx, roomID, userID, event.MembershipJoin, event.MembershipInvite) || (user != nil && user.HolderOnly) { return historyGone, nil, nil } else if user == nil { return historyWaits, nil, nil } devices, err := c.TrustedDevices(ctx, userID) if err != nil { return historyWaits, nil, fmt.Errorf("failed to read the trusted devices of %s: %w", userID, err) } else if len(devices) == 0 { return historyWaits, nil, nil } return historyGoes, devices, nil } // historyReaders returns who reads an encrypted room as its owner's members: the switched-on user whose // login receives its portal, and that login's members; nobody for a room that is not encrypted or no // portal of a switched-on user's, or that the user left (ownerLeft), as roomMembers has them. Unlike // roomMembers it reports what it could not read, which leaves the rows to the next send. func (k *Kit) historyReaders(ctx context.Context, roomID id.RoomID) (id.UserID, []id.UserID, error) { if !k.isEncrypted(ctx, roomID) { return "", nil, nil } login, owner, err := roomLogin(ctx, k.db, k.br.ID, roomID) if err != nil { return "", nil, fmt.Errorf("failed to read whose portal %s is: %w", roomID, err) } else if login == "" || k.user(owner) == nil || k.ownerLeft(ctx, roomID, owner) { return "", nil, nil } return owner, k.membersOf(owner)[login], nil } // roomLogin returns the login whose portal a room is, with the login's user; "" for a room that is no // portal of a login's. func roomLogin(ctx context.Context, db *dbutil.Database, bridgeID networkid.BridgeID, roomID id.RoomID) (networkid.UserLoginID, id.UserID, error) { var login networkid.UserLoginID var userID id.UserID err := db.QueryRow(ctx, ` SELECT p.receiver, u.user_mxid FROM portal p JOIN user_login u ON u.bridge_id=p.bridge_id AND u.id=p.receiver WHERE p.bridge_id=$1 AND p.mxid=$2 `, bridgeID, roomID).Scan(&login, &userID) if errors.Is(err, sql.ErrNoRows) { return "", "", nil } return login, userID, err } // historyBundle is a room's key bundle: every session of the room the bridge has, from the first index // it has. A session that does not export is left out. func (k *Kit) historyBundle(ctx context.Context, mach *crypto.OlmMachine, roomID id.RoomID) (*roomKeyBundle, error) { bundle := &roomKeyBundle{RoomKeys: []historyKey{}, Withheld: []any{}} err := mach.CryptoStore.GetGroupSessionsForRoom(ctx, roomID).Iter(func(session *crypto.InboundGroupSession) (bool, error) { key, err := session.Internal.Export(session.Internal.FirstKnownIndex()) if err != nil { zerolog.Ctx(ctx).Err(err).Stringer("room_id", roomID).Stringer("session_id", session.ID()). Msg("Leaving a session that does not export out of the room's key bundle") return true, nil } bundle.RoomKeys = append(bundle.RoomKeys, historyKey{ Algorithm: id.AlgorithmMegolmV1, RoomID: roomID, SenderKey: session.SenderKey, SessionID: session.ID(), SessionKey: string(key), SenderClaimedKeys: crypto.SenderClaimedKeys{Ed25519: session.SigningKey}, }) return true, nil }) return bundle, err } // historyFile uploads a room's key bundle as an encrypted file, written down for deletion under the room // before its key goes anywhere: it goes with the room or the room's retention, whether the key reached a // device or not. A bridge without the API, or whose database does not take the row to write down, keeps // the bundle for later: no key goes to a file the deletion list might not name (one the database did not // take is still written down later, but lost if the bridge stops first). func (k *Kit) historyFile(ctx context.Context, roomID id.RoomID, bundle *roomKeyBundle) (*event.EncryptedFileInfo, error) { if k.refs == nil { return nil, fmt.Errorf("not sending the keys of %s: %s is not set, so their file could not be listed for deletion", roomID, apiURLEnv) } data, err := json.Marshal(bundle) if err != nil { return nil, err } file, err := k.encryptAndUpload(ctx, data) if err != nil { return nil, fmt.Errorf("failed to upload the key bundle of %s: %w", roomID, err) } mediaID, ok := k.localMedia(string(file.URL)) if !ok { return nil, fmt.Errorf("the homeserver gave the key bundle of %s an address of another server: %s", roomID, file.URL) } ref := mediaRef{RoomID: roomID, EventID: historyKeysEvent(mediaID), Part: refEvent, MediaIDs: []string{mediaID}, OriginTS: time.Now().UnixMilli()} if err = k.queueRefs(ctx, []mediaRef{ref}); err != nil { return nil, fmt.Errorf("not sending the keys of %s: their file could not be kept for the deletion list: %w", roomID, err) } return file, nil } // forgetHistory forgets a row whose bundle went, or whose identity no longer reads the room, unless it // was noted again meanwhile. func (k *Kit) forgetHistory(ctx context.Context, due historyDue) error { if err := k.store.historySent(ctx, due); err != nil { return fmt.Errorf("failed to forget that the keys of %s go to %s: %w", due.RoomID, due.UserID, err) } return nil }