// 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" "errors" "fmt" "slices" "time" "maunium.net/go/mautrix" "maunium.net/go/mautrix/bridgev2/matrix" "maunium.net/go/mautrix/crypto" "maunium.net/go/mautrix/crypto/signatures" "maunium.net/go/mautrix/event" "maunium.net/go/mautrix/id" ) // Room keys go only to the devices a switched-on user's identity cross-signed (work plan 4.2 ④), and // mautrix starts a new outbound session for a room only when the user's devices are added or removed. // A device the user approves later (an existing device that gets cross-signed) would then miss the // rest of every current session. So the extension looks at the trust of a switched-on user's devices // whenever their device list changes, and when a device has become trusted it drops the outbound // sessions of the rooms shared with them: the next message's session reaches that device too (T3). // trustInterval is how often the switched-on users' keys are fetched again and their devices' trust // looked at without a device list change: for a change whose sync was handled past mautrix's time // limit, and for one whose key fetch failed, which mautrix does not try again (HandleDeviceLists drops // the error, and nothing marks the user's device list outdated). Their rooms are brought in line with // their members as often (members.go), for what a sync could not do. const trustInterval = 10 * time.Minute // identityCrypto is what the identity checks need from the bridge's Olm machine (machineCrypto). type identityCrypto interface { // MasterKey is the user's master key as the homeserver last gave it, "" when they have none. MasterKey(ctx context.Context, userID id.UserID) (id.Ed25519, error) // FirstSeenMasterKey is the master key mautrix trusts the user's devices by (TOFU): the first one it // saw, one accepted since, or NeverTrust's marker. FirstSeenMasterKey(ctx context.Context, userID id.UserID) (id.Ed25519, error) // TrustedDevices are the user's devices trusted as cross-signed-tofu or more, by signing key. TrustedDevices(ctx context.Context, userID id.UserID) (map[id.DeviceID]id.Ed25519, error) // FetchKeys asks the homeserver again for the users' devices and cross-signing keys. FetchKeys(ctx context.Context, users []id.UserID) error // DevicesChanged drops the outbound sessions of the rooms shared with the user. DevicesChanged(ctx context.Context, userID id.UserID) // DropSessions is DevicesChanged for a drop that must happen: it reports what failed. DropSessions(ctx context.Context, userID id.UserID) error // MasterKeySignedBy reports whether the homeserver shows master as the user's master key with a // signature by one of signers, checked on the key object it gives. MasterKeySignedBy(ctx context.Context, userID id.UserID, master id.Ed25519, signers []keySigner) (bool, error) // AcceptMasterKey makes mautrix trust the user's current master key as if first seen (TOFU). AcceptMasterKey(ctx context.Context, userID id.UserID, key id.Ed25519) error // SendToDevice sends an Olm-encrypted to-device event to one of the user's devices, if it still has // the signing key it was known by. SendToDevice(ctx context.Context, userID id.UserID, deviceID id.DeviceID, signingKey id.Ed25519, evtType event.Type, content any) error // NeverTrust makes mautrix trust none of the user's devices from now on, whatever master key the // homeserver shows for them. It reports whether mautrix could have trusted one until now. NeverTrust(ctx context.Context, userID id.UserID) (bool, error) } // keySigner is a key that may have signed a master key, under the name a signature gives it: a // cross-signing key's name is its public key, a device's is its device ID. type keySigner struct { Name string Key id.Ed25519 } // distrustedFirstSeen is what the extension puts as the first master key mautrix saw for a holder // (api.go enableHolderOnly), and for a switched-on user whose new master key could not be pinned, // until the next look (identity.go acceptIdentity). mautrix trusts a user's cross-signed devices on first use only while // their master key is the first one it saw (OlmMachine.ResolveTrustContext), and never replaces the // first one itself (SQLCryptoStore.PutCrossSigningKey), so with this no key the homeserver shows is // ever the first: it is not base64, and every key is. It is 43 characters, the width of the column. const distrustedFirstSeen id.Ed25519 = "xessenger:holder-only:never-trust-this-user" type machineCrypto struct { mach *crypto.OlmMachine } func (m machineCrypto) MasterKey(ctx context.Context, userID id.UserID) (id.Ed25519, error) { keys, err := m.mach.CryptoStore.GetCrossSigningKeys(ctx, userID) if err != nil { return "", err } return keys[id.XSUsageMaster].Key, nil } func (m machineCrypto) FirstSeenMasterKey(ctx context.Context, userID id.UserID) (id.Ed25519, error) { keys, err := m.mach.CryptoStore.GetCrossSigningKeys(ctx, userID) if err != nil { return "", err } return keys[id.XSUsageMaster].First, nil } func (m machineCrypto) TrustedDevices(ctx context.Context, userID id.UserID) (map[id.DeviceID]id.Ed25519, error) { devices, err := m.mach.CryptoStore.GetDevices(ctx, userID) if err != nil { return nil, err } trusted := make(map[id.DeviceID]id.Ed25519, len(devices)) for deviceID, device := range devices { trust, err := m.mach.ResolveTrustContext(ctx, device) if err != nil { return nil, err } if trust >= id.TrustStateCrossSignedTOFU { trusted[deviceID] = device.SigningKey } } return trusted, nil } func (m machineCrypto) FetchKeys(ctx context.Context, users []id.UserID) error { _, err := m.mach.FetchKeys(ctx, users, true) return err } func (m machineCrypto) DevicesChanged(ctx context.Context, userID id.UserID) { m.mach.OnDevicesChanged(ctx, userID) } // DropSessions drops the outbound sessions of the rooms shared with the user as mautrix does when their // devices change (OlmMachine.OnDevicesChanged), which only logs what fails, and also when its device // change key rotation is off: devices that must not read on are cut off either way. func (m machineCrypto) DropSessions(ctx context.Context, userID id.UserID) error { rooms, err := m.mach.StateStore.FindSharedRooms(ctx, userID) if err != nil { return fmt.Errorf("failed to find the rooms shared with the user: %w", err) } var errs []error for _, roomID := range rooms { if err = m.mach.CryptoStore.RemoveOutboundGroupSession(ctx, roomID); err != nil { errs = append(errs, fmt.Errorf("failed to drop the outbound session of %s: %w", roomID, err)) } } return errors.Join(errs...) } func (m machineCrypto) MasterKeySignedBy(ctx context.Context, userID id.UserID, master id.Ed25519, signers []keySigner) (bool, error) { resp, err := m.mach.Client.QueryKeys(ctx, &mautrix.ReqQueryKeys{DeviceKeys: mautrix.DeviceKeysRequest{userID: mautrix.DeviceIDList{}}}) if err != nil { return false, err } return masterKeySignedBy(resp.MasterKeys[userID], userID, master, signers), nil } // masterKeySignedBy reports whether keys is the user's master key master with a signature by one of // signers. mautrix's signature table cannot tell: it keeps a signature by signed and signing key only, // so a device's signature on itself, or the master key's on the self-signing key, would read as a // signature on a master key that is that device's or that self-signing key's public key. func masterKeySignedBy(keys mautrix.CrossSigningKeys, userID id.UserID, master id.Ed25519, signers []keySigner) bool { if keys.UserID != userID || !slices.Contains(keys.Usage, id.XSUsageMaster) || len(keys.Keys) != 1 || keys.Keys[id.NewKeyID(id.KeyAlgorithmEd25519, master.String())] != master { return false } for _, signer := range signers { if signed, err := signatures.VerifySignatureJSON(keys, userID, signer.Name, signer.Key); err == nil && signed { return true } } return false } func (m machineCrypto) AcceptMasterKey(ctx context.Context, userID id.UserID, key id.Ed25519) error { return m.mach.CryptoStore.ResetMasterKeyTOFU(ctx, userID, key) } // errDeviceGone is a device a to-device event cannot reach as the device meant: it is gone, or listed // with another signing key. var errDeviceGone = errors.New("the device is not there as it was") func (m machineCrypto) SendToDevice(ctx context.Context, userID id.UserID, deviceID id.DeviceID, signingKey id.Ed25519, evtType event.Type, content any) error { device, err := m.mach.CryptoStore.GetDevice(ctx, userID, deviceID) if err != nil { return err } else if device == nil || device.Deleted { return fmt.Errorf("%w: device %s is gone", errDeviceGone, deviceID) } else if device.SigningKey != signingKey { return fmt.Errorf("%w: device %s has another signing key now", errDeviceGone, deviceID) } return m.mach.SendEncryptedToDevice(ctx, device, evtType, event.Content{Parsed: content}) } func (m machineCrypto) NeverTrust(ctx context.Context, userID id.UserID) (bool, error) { keys, err := m.mach.CryptoStore.GetCrossSigningKeys(ctx, userID) if err != nil { return false, err } master, seen := keys[id.XSUsageMaster] if seen && master.First == distrustedFirstSeen { return false, nil } store := sqlCryptoStore(m.mach.CryptoStore) if store == nil { return false, fmt.Errorf("the crypto store is a %T, not the SQL one", m.mach.CryptoStore) } // With no master key seen yet, the row holds only the marker: a key the homeserver shows later // replaces its key, never its first one. _, err = store.DB.Exec(ctx, ` INSERT INTO crypto_cross_signing_keys (user_id, usage, key, first_seen_key) VALUES ($1, $2, $3, $3) ON CONFLICT (user_id, usage) DO UPDATE SET first_seen_key=excluded.first_seen_key `, userID, id.XSUsageMaster, distrustedFirstSeen) return seen, err } // sqlCryptoStore is mautrix's SQL crypto store, which bridgev2 gives the Olm machine inside its own // (bridgev2/matrix.SQLCryptoStore, which embeds it); nil for another kind of store. func sqlCryptoStore(store crypto.Store) *crypto.SQLCryptoStore { switch store := store.(type) { case *crypto.SQLCryptoStore: return store case *matrix.SQLCryptoStore: return store.SQLCryptoStore } return nil } // checkTrust compares the user's trusted devices with the ones last seen. When one has become trusted // (a new device ID, or a known one listed again with another signing key, which mautrix takes with // mautrix-device-keys.patch), the outbound sessions of the rooms shared with the user are dropped. A // holder's devices stay untrusted. func (k *Kit) checkTrust(ctx context.Context, c identityCrypto, user *e2eeUser) error { k.trustLock.Lock() defer k.trustLock.Unlock() // The caller read the user before it waited for trustLock, and a holder switched on or a new // identity accepted meanwhile (both under trustLock) replaced them: look at them as they are now. if user = k.user(user.MXID); user == nil { return nil } if user.HolderOnly { if couldTrust, err := k.distrust(ctx, c, user.MXID); err != nil { return err } else if couldTrust { k.log.Warn().Stringer("user_id", user.MXID).Msg("mautrix could trust a holder's devices again; distrusted them and started new outbound sessions") } return nil } master, err := c.MasterKey(ctx, user.MXID) if err != nil { return fmt.Errorf("failed to read the master key: %w", err) } if master != user.PinnedMasterKey { // Until a new identity is accepted (identity.go) mautrix trusts none of its devices, and the // devices the pinned identity cross-signed are kept as last seen. return k.identityChanged(ctx, c, user, master) } if err = k.dropWaitingReset(ctx, user); err != nil { return err } // mautrix trusts the user's devices by the pinned key. A crypto store that first saw another key, // a holder switch whose save failed after NeverTrust, a switch-on whose key could not be trusted // or whose rooms could not be noted once saved (api.go enable) or a new key that could not be // pinned (acceptIdentity) leaves it trusting none of them. if first, err := c.FirstSeenMasterKey(ctx, user.MXID); err != nil { return fmt.Errorf("failed to read the master key mautrix trusts: %w", err) } else if master != "" && first != master { k.log.Warn().Stringer("user_id", user.MXID).Msg("mautrix did not trust a switched-on user's pinned master key; trusting it again") // The keys of what came before in the rooms they are in go to them once it does (history.go), // noted first: this check notes them again the next time while the bridge database takes none. if err = k.noteHistoryOf(ctx, user.MXID); err != nil { return err } if err = c.AcceptMasterKey(ctx, user.MXID, master); err != nil { return fmt.Errorf("failed to trust the pinned master key again: %w", err) } // The sessions started meanwhile left their devices out, and the metadata sent into the rooms // they are a member of. c.DevicesChanged(ctx, user.MXID) go k.resendMetaTo(k.backgroundContext(), user.MXID) } trusted, err := c.TrustedDevices(ctx, user.MXID) if err != nil { return fmt.Errorf("failed to read the trusted devices: %w", err) } seen, err := k.store.trustedDevices(ctx, user.MXID) if err != nil { return fmt.Errorf("failed to read the devices last seen: %w", err) } rose := false for deviceID, key := range trusted { if seen[deviceID] != key { rose = true break } } if rose { k.log.Debug().Stringer("user_id", user.MXID).Msg("A device of a switched-on user became trusted, starting new outbound sessions") c.DevicesChanged(ctx, user.MXID) } if rose || len(trusted) != len(seen) { if err = k.store.putTrustedDevices(ctx, user.MXID, trusted); err != nil { return fmt.Errorf("failed to save the trusted devices: %w", err) } } return nil } // distrust keeps mautrix from trusting any device of the user. If it could have trusted one until // now, the next message in each room shared with them starts a session without their devices. Called // with trustLock held. func (k *Kit) distrust(ctx context.Context, c identityCrypto, userID id.UserID) (bool, error) { couldTrust, err := c.NeverTrust(ctx, userID) if err != nil { return false, fmt.Errorf("failed to distrust the user's devices: %w", err) } if couldTrust { c.DevicesChanged(ctx, userID) } return couldTrust, nil } // distrustHolders puts back what keeps mautrix from trusting the holders' devices before the Olm // machine is used: a crypto store made anew starts without it. Encryption does not start when it // fails, as mautrix would then trust a holder's devices by the first master key it sees. func (k *Kit) distrustHolders(ctx context.Context, c identityCrypto) error { k.trustLock.Lock() defer k.trustLock.Unlock() var errs []error k.users.Range(func(_, value any) bool { if user := value.(*e2eeUser); user.HolderOnly { if _, err := k.distrust(ctx, c, user.MXID); err != nil { errs = append(errs, fmt.Errorf("%s: %w", user.MXID, err)) } } return true }) return errors.Join(errs...) } // checkUsers looks at the trust of the switched-on users among userIDs. func (k *Kit) checkUsers(ctx context.Context, c identityCrypto, userIDs []id.UserID) { for _, userID := range userIDs { user := k.user(userID) if user == nil { continue } if err := k.checkTrust(ctx, c, user); err != nil { k.log.Err(err).Stringer("user_id", userID).Msg("Failed to check the trust of a switched-on user's devices") } } } // switchedOn lists the switched-on users. func (k *Kit) switchedOn() []id.UserID { var users []id.UserID k.users.Range(func(key, _ any) bool { users = append(users, key.(id.UserID)) return true }) return users } // watchTrust looks at the switched-on users' keys and brings their rooms in line with their members // when encryption (re)starts, then again every trustInterval until the bridge stops or encryption is // reset, and sends the keys of rooms still due to those who read them late (history.go) and the room // metadata noted to go again (resendRoomMeta). It also lets the answers of week-old requests done once // go (forgetOldRequests). func (k *Kit) watchTrust(ctx context.Context, mach *crypto.OlmMachine) { c := machineCrypto{mach: mach} k.forgetOldRequests(ctx) k.recheckUsers(ctx, c) k.syncAllMembers() k.sendHeldState(ctx) k.resendRoomMeta(ctx) k.queueHistory() ticker := time.NewTicker(trustInterval) defer ticker.Stop() for { select { case <-ctx.Done(): return case <-ticker.C: if k.machine() != mach { // Encryption was reset: the new machine has its own watch. return } k.forgetOldRequests(ctx) k.recheckUsers(ctx, c) k.syncAllMembers() k.sendHeldState(ctx) k.resendRoomMeta(ctx) k.queueHistory() } } } // recheckUsers fetches the switched-on users' keys from the homeserver, then looks at their devices' // trust (with what the store has if the fetch failed). func (k *Kit) recheckUsers(ctx context.Context, c identityCrypto) { users := k.switchedOn() if len(users) == 0 { return } if err := c.FetchKeys(ctx, users); err != nil { k.log.Err(err).Msg("Failed to fetch the switched-on users' keys") } k.checkUsers(ctx, c, users) } // identitySyncer is the syncer of the bot's crypto client (bridgev2's, which hands the sync to the // Olm machine) with the extension's checks after each sync: a switched-on user whose device list // changed gets their devices' trust looked at again, after mautrix fetched their keys. type identitySyncer struct { mautrix.Syncer kit *Kit mach *crypto.OlmMachine } func (s *identitySyncer) ProcessResponse(ctx context.Context, resp *mautrix.RespSync, since string) error { if s.kit.active() && len(resp.ToDevice.Events) > 0 { resp.ToDevice.Events = s.kit.takeIdentityEvents(ctx, s.mach, resp.ToDevice.Events) } err := s.Syncer.ProcessResponse(ctx, resp, since) if s.kit.active() && len(resp.DeviceLists.Changed) > 0 { s.kit.checkUsers(ctx, machineCrypto{mach: s.mach}, resp.DeviceLists.Changed) } return err }