// 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" "encoding/json" "errors" "runtime/debug" "slices" "time" "github.com/rs/zerolog" "maunium.net/go/mautrix/bridgev2" "maunium.net/go/mautrix/bridgev2/networkid" "maunium.net/go/mautrix/crypto" "maunium.net/go/mautrix/event" "maunium.net/go/mautrix/id" ) // The app asks the bridge for what only the bridge can read or do for a switched-on user, and what the // server must not see (QA-289): a mail's quote or original layout, a mailbox's spam notes, a group to // make. It asks the bridge bot's device over Olm, with a to-device com.xessenger.bridge.request {v, // request_id, method, login_id, params}, and the bot answers that device alone, over Olm too, with a // com.xessenger.bridge.response {v, request_id, method} and a result, a file holding one, or an error. // To-device events leave nothing in any room, and a bridge that does not know these drops them in // mautrix's Olm machine, which takes every to-device event: none reaches a portal, let alone the // messenger. // // Only switched-on users' requests are taken (takeIdentityEvents decrypts them), from a device their // pinned identity cross-signed, by the key the extension saw it trusted with (requestTrusted, as for an // identity rejection). The login's user may call any method, its members only one about a room of the // login (Method.Room) while the user is in it (roomMembers). Anybody else is answered not_allowed, and // so is one who no longer may ask once the method found its result, or once the file holding it is up // (stillAllowed). // // A result goes in the answer up to MaxInlineResult, which keeps the Olm event under 64 KiB. A larger // result of a method about a room goes up as an encrypted file instead, written down for deletion under // the room before the answer goes (mediarefs.go): it goes with the room or the room's retention. A // method about no room keeps its results small (the mail bridge's spam notes come in pages). // // Every bridge answers the methods of groups.go, finding people on the network and making groups of // them, besides the ones its connector gives (Options.Methods). // Method is something the app may ask of the bridge over Olm (requests.go). type Method struct { // Name is how requests name the method, such as "email.quote". Name string // Room is whether the method is about a room of the login, which params.room_id names: the login's // members may call it too, about a room of the login while its user is in it. Room bool // Call answers a request with the JSON the answer carries. It returns ErrRequestNotFound when there // is nothing to answer with and ErrBadRequest for params it cannot take; any other error is // answered as unavailable. Call func(ctx context.Context, req *Request) (json.RawMessage, error) // Timeout bounds Call; requestTimeout when zero. Timeout time.Duration } // Request is what the app asked of the bridge, from somebody who may ask it. type Request struct { // Login is the login the request names, which the bridge acts as. Login *bridgev2.UserLogin // Portal is the portal of the room a method about a room is asked about, nil for another method. Portal *bridgev2.Portal // Sender is who asked: the login's user, or one of its members. Sender id.UserID // Method is the name of the method asked (Method.Name). Method string // Params are the method's own. Params json.RawMessage // RequestID is the app's ID of the request: a method that must not do twice what it is asked once // keeps its answer under it, with the method, the room and the sender (groups.go, answerOnce). RequestID string } var ( // ErrRequestNotFound is what a Method's Call returns when there is nothing to answer with. ErrRequestNotFound = errors.New("nothing to answer the request with") // ErrBadRequest is what a Method's Call returns for params it cannot take. ErrBadRequest = errors.New("the request's params cannot be taken") // ErrUnsupported is what a Method's Call returns when the network cannot do what is asked: it is // answered as a method the bridge does not have. ErrUnsupported = errors.New("the network cannot do what the request asks") ) // MaxInlineResult is the most of a result an answer carries itself: with what an Olm event wraps around // it, encrypted, the event stays under 64 KiB. const MaxInlineResult = 44 << 10 var ( eventBridgeRequest = event.Type{Type: "com.xessenger.bridge.request", Class: event.ToDeviceEventType} eventBridgeResponse = event.Type{Type: "com.xessenger.bridge.response", Class: event.ToDeviceEventType} ) // The errors an answer gives in place of a result. const ( requestNotAllowed = "not_allowed" requestNotFound = "not_found" requestUnavailable = "unavailable" requestBadRequest = "bad_request" requestUnknownMethod = "unknown_method" ) const ( // maxRequestField bounds request_id, method and room_id, which an answer may repeat. maxRequestField = 255 // requestTimeout bounds a method's call unless it has its own (Method.Timeout), as the provisioning // API bounds its own. requestTimeout = 25 * time.Second // requestSlots is how many requests are answered at once; one more is answered unavailable. requestSlots = 8 ) // bridgeRequest is a com.xessenger.bridge.request. type bridgeRequest struct { Version int `json:"v"` RequestID string `json:"request_id"` Method string `json:"method"` LoginID networkid.UserLoginID `json:"login_id"` Params json.RawMessage `json:"params,omitempty"` } // bridgeResponse is a com.xessenger.bridge.response: a result, a file holding one, or an error. type bridgeResponse struct { Version int `json:"v"` RequestID string `json:"request_id"` Method string `json:"method"` Result json.RawMessage `json:"result,omitempty"` File *event.EncryptedFileInfo `json:"file,omitempty"` Error string `json:"error,omitempty"` } // installRequests takes the methods every bridge answers (groups.go) and the connector's // (Options.Methods); one without a name or a call, or named again, is left out. func (k *Kit) installRequests() { k.requestSlots = make(chan struct{}, requestSlots) k.methods = make(map[string]Method) for _, method := range append(k.networkMethods(), k.opts.Methods...) { if method.Name == "" || len(method.Name) > maxRequestField || method.Call == nil { k.log.Error().Str("method", method.Name).Msg("Leaving out a method without a name or a call") continue } else if _, again := k.methods[method.Name]; again { k.log.Error().Str("method", method.Name).Msg("Leaving out a method named again") continue } k.methods[method.Name] = method } } // takeRequest answers a request in the background: a method may take as long as the network does, and // the sync goes on meanwhile. A request without a request ID to answer to, or from a device mautrix // does not know by the key it signed with, is dropped: there is nobody to answer. func (k *Kit) takeRequest(user *e2eeUser, evt *crypto.DecryptedOlmEvent) { log := k.log.With().Stringer("sender", user.MXID).Logger() var fields struct { RequestID string `json:"request_id"` } if json.Unmarshal(evt.Content.VeryRaw, &fields) != nil || fields.RequestID == "" || len(fields.RequestID) > maxRequestField { log.Warn().Msg("Dropping a request without a request ID to answer to") return } device := evt.SenderDevice if device == nil || device.UserID != user.MXID || evt.Keys.Ed25519 != device.SigningKey { log.Warn().Msg("Dropping a request from a device mautrix does not know") return } req := &bridgeRequest{RequestID: fields.RequestID} if json.Unmarshal(evt.Content.VeryRaw, req) != nil || len(req.Method) > maxRequestField { // Answered as a request of no version, which nothing takes. req = &bridgeRequest{RequestID: fields.RequestID} } log = log.With().Stringer("device_id", device.DeviceID).Str("request_id", req.RequestID).Str("method", req.Method).Logger() go func() { // As bridgev2 recovers its handlers: a request that fails this way must not stop the bridge. defer func() { if err := recover(); err != nil { log.Error().Any("panic", err).Bytes("stack", debug.Stack()).Msg("Panic while answering a request") } }() k.answerRequest(log.WithContext(k.backgroundContext()), user.MXID, device, req) }() } // answerRequest answers a request to the device that made it. func (k *Kit) answerRequest(ctx context.Context, sender id.UserID, device *id.Device, req *bridgeRequest) { answer := &bridgeResponse{Version: 1, RequestID: req.RequestID, Method: req.Method} answer.Result, answer.File, answer.Error = k.callMethod(ctx, sender, device, req) k.sendAnswer(ctx, sender, device, answer) } // callMethod calls the method a request asks for when its sender may ask it, and returns the result to // answer with, a file holding it, or the error in its place. func (k *Kit) callMethod(ctx context.Context, sender id.UserID, device *id.Device, req *bridgeRequest) (json.RawMessage, *event.EncryptedFileInfo, string) { log := zerolog.Ctx(ctx) if !k.requestTrusted(ctx, sender, device) { log.Warn().Msg("Refusing a request from a device the sender's pinned identity did not cross-sign") return nil, nil, requestNotAllowed } else if req.Version != 1 { return nil, nil, requestBadRequest } method, ok := k.methods[req.Method] if !ok { return nil, nil, requestUnknownMethod } call, refusal := k.requestOf(ctx, sender, method, req) if refusal != "" { return nil, nil, refusal } select { case k.requestSlots <- struct{}{}: defer func() { <-k.requestSlots }() default: log.Warn().Int("slots", requestSlots).Msg("Too many requests are being answered; answering unavailable") return nil, nil, requestUnavailable } timeout := method.Timeout if timeout <= 0 { timeout = requestTimeout } callCtx, cancel := context.WithTimeout(ctx, timeout) result, err := method.Call(callCtx, call) cancel() switch { case errors.Is(err, ErrRequestNotFound): return nil, nil, requestNotFound case errors.Is(err, ErrBadRequest): return nil, nil, requestBadRequest case errors.Is(err, ErrUnsupported): return nil, nil, requestUnknownMethod case err != nil: log.Err(err).Msg("Failed to answer a request") return nil, nil, requestUnavailable } if refusal := k.stillAllowed(ctx, sender, device, method, req); refusal != "" { return nil, nil, refusal } switch { case result == nil: return json.RawMessage("null"), nil, "" case !json.Valid(result): log.Error().Msg("A method answered with what is not JSON") return nil, nil, requestUnavailable case len(result) <= MaxInlineResult: return result, nil, "" } file, refusal := k.resultFile(ctx, call, result) if refusal != "" { return nil, nil, refusal } // Going up takes a while: the file's key goes only to somebody who may still ask once it is up. The // file is written down under the room by then, and goes with it. if refusal := k.stillAllowed(ctx, sender, device, method, req); refusal != "" { return nil, nil, refusal } return nil, file, "" } // requestTrusted reports whether a request came from a device the sender's pinned identity // cross-signed, under the key the extension saw it trusted with, as an identity rejection must // (identityRejected). The sender is read again under trustLock, which a switch-off or a new identity // takes first. func (k *Kit) requestTrusted(ctx context.Context, sender id.UserID, device *id.Device) bool { k.trustLock.Lock() defer k.trustLock.Unlock() user := k.user(sender) if user == nil || user.HolderOnly || user.PinnedMasterKey == "" { return false } pinned, err := k.store.trustedDevices(ctx, sender) if err != nil { zerolog.Ctx(ctx).Err(err).Msg("Failed to read the pinned identity's devices for a request") return false } return pinned[device.DeviceID] != "" && pinned[device.DeviceID] == device.SigningKey } // requestOf returns the request a method is called with when its sender may make it: the login's user // any, the login's members one about a room of the login while the user is in it (roomMembers). // Otherwise it returns the error to answer with. func (k *Kit) requestOf(ctx context.Context, sender id.UserID, method Method, req *bridgeRequest) (*Request, string) { log := zerolog.Ctx(ctx) login, err := k.br.GetExistingUserLoginByID(ctx, req.LoginID) if err != nil { log.Err(err).Msg("Failed to get the login a request names") return nil, requestUnavailable } else if login == nil { log.Warn().Msg("Refusing a request of a login the bridge does not have") return nil, requestNotAllowed } call := &Request{Login: login, Sender: sender, Method: method.Name, Params: req.Params, RequestID: req.RequestID} if !method.Room { if sender != login.UserMXID { log.Warn().Msg("Refusing a request of a login from somebody but its user") return nil, requestNotAllowed } return call, "" } var params struct { RoomID id.RoomID `json:"room_id"` } if json.Unmarshal(req.Params, ¶ms) != nil || params.RoomID == "" || len(params.RoomID) > maxRequestField { return nil, requestBadRequest } portal, err := k.br.GetPortalByMXID(ctx, params.RoomID) if err != nil { log.Err(err).Msg("Failed to get the portal of a request's room") return nil, requestUnavailable } else if portal == nil || portal.Receiver != login.ID { log.Warn().Msg("Refusing a request about a room that is not the login's") return nil, requestNotAllowed } if sender != login.UserMXID { owner, members := k.roomMembers(ctx, portal.MXID) if owner != login.UserMXID || !slices.Contains(members, sender) { log.Warn().Msg("Refusing a request from somebody who does not read the room as the login's user") return nil, requestNotAllowed } } call.Portal = portal return call, "" } // stillAllowed asks requestTrusted and requestOf again once a method found its result, and once more // when the file holding it is up: what it found goes only to somebody who may still ask, not to one // switched off, given a new identity or no longer reading the room meanwhile. It returns the error to // answer with instead. func (k *Kit) stillAllowed(ctx context.Context, sender id.UserID, device *id.Device, method Method, req *bridgeRequest) string { if !k.requestTrusted(ctx, sender, device) { zerolog.Ctx(ctx).Warn().Msg("Not answering a request whose sender may no longer ask") return requestNotAllowed } _, refusal := k.requestOf(ctx, sender, method, req) return refusal } // answerFileEvent is the event a result too large for an answer is written down under, in the room of // its request (resultFile). No Matrix event takes this ID; the API takes it as any other. func answerFileEvent(mediaID string) id.EventID { return id.EventID("$xessenger-answer:" + mediaID) } // resultFile uploads a result too large for an answer as an encrypted file, written down for deletion // under the room the request is about before the answer goes: it goes with the room or the room's // retention, whether the answer reached the device or not. A method about no room has no room to write // one under, and its result too large is answered unavailable. func (k *Kit) resultFile(ctx context.Context, req *Request, result json.RawMessage) (*event.EncryptedFileInfo, string) { log := zerolog.Ctx(ctx) if req.Portal == nil { log.Error().Int("size", len(result)).Msg("A method about no room answered more than an answer carries") return nil, requestUnavailable } else if k.refs == nil { log.Error().Msgf("Not answering with a file: %s is not set, so it could not be listed for deletion", apiURLEnv) return nil, requestUnavailable } file, err := k.encryptAndUpload(ctx, result) if err != nil { log.Err(err).Msg("Failed to upload a result too large for an answer") return nil, requestUnavailable } mediaID, ok := k.localMedia(string(file.URL)) if !ok { log.Error().Str("url", string(file.URL)).Msg("The homeserver gave the answer's file an address of another server") return nil, requestUnavailable } // A row the bridge database does not take is kept for its next round (queueRefs). _ = k.queueRefs(ctx, []mediaRef{{RoomID: req.Portal.MXID, EventID: answerFileEvent(mediaID), Part: refEvent, MediaIDs: []string{mediaID}, OriginTS: time.Now().UnixMilli()}}) return file, "" } // sendAnswer sends an answer over Olm to the device that made the request, if it still has the signing // key it asked with. func (k *Kit) sendAnswer(ctx context.Context, sender id.UserID, device *id.Device, answer *bridgeResponse) { log := zerolog.Ctx(ctx) mach := k.machine() if mach == nil { log.Error().Msg("Not answering a request without the Olm machine") return } if err := (machineCrypto{mach: mach}).SendToDevice(ctx, sender, device.DeviceID, device.SigningKey, eventBridgeResponse, answer); err != nil { log.Err(err).Msg("Failed to answer a request") return } log.Debug().Str("error", answer.Error).Bool("file", answer.File != nil).Msg("Answered a request") }