// 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 ( "bytes" "encoding/json" "errors" "fmt" "io" "mime" "net/http" "os" "strconv" "sync" "time" "xessenger/bridgekit/loginseal" ) // The routes starting and moving a sign-in (bridgev2/matrix/provisioninglogin.go PostLoginStart, // PostLoginStep and PostLoginStepCancel) on the appservice router, where the provisioning API is // mounted. const ( loginStartPattern = "POST /_matrix/provision/v3/login/start/{flowID}" loginStepPattern = "POST /_matrix/provision/v3/login/step/{loginProcessID}/{stepID}/{stepType}" ) // maxLoginStepBody bounds a sign-in step's body, sealed or not: cookies, the largest input, take a // few kilobytes. const maxLoginStepBody = 1 << 20 // loginOwnerTTL is how long the user who started a login process is kept: bridgev2 gives a login // process up after 30 minutes (PostLoginStart). const loginOwnerTTL = time.Hour // Errors answering sealed input that is refused, which the API passes on to the app. const ( // errNoLoginKey: the bridge has no login key yet (503), as while the attestation offers none. errNoLoginKey = "M_XESSENGER_LOGIN_NO_KEY" // errLoginKeyChanged: the input was sealed to another login key (412). The app fetches the // attestation again and seals the same step anew; the login process goes on. errLoginKeyChanged = "M_XESSENGER_LOGIN_KEY_CHANGED" // errLoginOpen: the input does not open for this bridge, user, login process and step, or changed // on the way (400). errLoginOpen = "M_XESSENGER_LOGIN_OPEN_FAILED" // errLoginEnvelope: the envelope, or the input in it, is not what the bridge takes (400). errLoginEnvelope = "M_XESSENGER_LOGIN_BAD_ENVELOPE" // errLoginNotOwner: the input came for another user than the one who started the login (403). errLoginNotOwner = "M_XESSENGER_LOGIN_NOT_OWNER" ) var ( // errLoginUnknown: nobody is known to have started the login process here, or long ago (404, as // bridgev2 answers a login it does not have). errLoginUnknown = errors.New("no user is known to have started the login process") errNotOwner = errors.New("the sealed input is not for the user who started the login") ) // secureLogins keeps a sign-in through the provisioning API to the account of the user who started it // (docs/e2ee/work-plan.md 4.11). bridgev2 serves a login's steps to whoever the provisioning API lets // in, and the API, which holds the provisioning secret, is not trusted with the sign-in. // // - The app seals a step's input (an app password, a code, cookies) to the enclave's login key for // its own Matrix user, the API forwards it as {"sealed": envelope}, and the extension opens it in // front of bridgev2 only for the user who started that login. bridgev2 then reads it as input // sent in the clear, which still passes as before. // - Every step the bridge answers is signed for the user who started the login, so that the app // shows a QR code, a pairing code or a link only when they are its own sign-in's: what the server // shows cannot be sealed. // // Without XESSENGER_LOGIN_KEY_FILE sealed input is refused and steps go unsigned; a key file that // cannot be used stops the bridge. func (k *Kit) secureLogins() error { key, err := loginseal.Default() if err != nil { return err } if key == nil { k.log.Info().Msg("No login key: sealed sign-in input will be refused and sign-in steps go unsigned") } else { if public := os.Getenv(loginseal.PublicKeyEnv); public != "" && public != key.PublicKey() { k.log.Error().Str("login_kid", key.Kid()). Msg("XESSENGER_LOGIN_PUBLIC_KEY is not the login key's: input sealed to it will not open") } if public := os.Getenv(loginseal.SigningPublicKeyEnv); public != "" && public != key.SigningPublicKey() { k.log.Error().Str("signing_kid", key.SigningKid()). Msg("XESSENGER_LOGIN_SIGNING_PUBLIC_KEY is not the login key's: the app will not take the steps signed here") } k.log.Info().Str("login_kid", key.Kid()).Str("signing_kid", key.SigningKid()). Msg("Sealed sign-in input will be opened for the user who started the sign-in, and its steps signed") } k.handleLogins(k.conn.AS.Router, key, newLoginOwners()) return nil } // handleLogins puts the extension in front of the routes starting and moving a sign-in. The router // serves bridgev2's provisioning API under /_matrix/provision/ (mounted once the bridge starts); the // routes here are more specific, so they come first, and hand every request on to it. func (k *Kit) handleLogins(router *http.ServeMux, key *loginseal.Key, owners *loginOwners) { router.HandleFunc(loginStartPattern, func(w http.ResponseWriter, r *http.Request) { // bridgev2 starts the login for this user: as given with the provisioning secret, or once it // is the Matrix token's own (checkMatrixAuth). The API always gives it. owner := r.URL.Query().Get("user_id") answer := askProvisioning(router, r) if loginID, stepType, ok := answeredStep(answer, ""); ok && owner != "" { owners.remember(loginID, owner) k.signStep(answer, key, owner) if stepType == "complete" { owners.forget(loginID) } } answer.send(w) }) router.HandleFunc(loginStepPattern, func(w http.ResponseWriter, r *http.Request) { body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, maxLoginStepBody)) if err != nil { var tooLarge *http.MaxBytesError if errors.As(err, &tooLarge) { writeError(w, http.StatusRequestEntityTooLarge, "M_TOO_LARGE", "Request body too large") } else { writeError(w, http.StatusBadRequest, "M_NOT_JSON", "Failed to read request body") } return } sealed, alone, ok := sealedInput(body) if !ok { r.Body = io.NopCloser(bytes.NewReader(body)) k.moveLogin(w, r, router, key, owners) return } // Only the API sends sealed input, with the provisioning secret, for the user who started the // login: both are checked before anything is opened. bridgev2 checks the step once it is. k.authenticate(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { k.openLoginStep(w, r, router, key, owners, sealed, alone) })).ServeHTTP(w, r) }) } // sealedInput finds the envelope in {"sealed": {…}}. Input sent in the clear is an object of strings, // so a field named "sealed" holding a string is not one. alone is false when other fields come with it. func sealedInput(body []byte) (sealed json.RawMessage, alone, ok bool) { var fields map[string]json.RawMessage if json.Unmarshal(body, &fields) != nil { return nil, false, false } sealed = bytes.TrimSpace(fields["sealed"]) if len(sealed) == 0 || sealed[0] != '{' { return nil, false, false } return sealed, len(fields) == 1, true } func (k *Kit) openLoginStep(w http.ResponseWriter, r *http.Request, router *http.ServeMux, key *loginseal.Key, owners *loginOwners, sealed json.RawMessage, alone bool) { loginID, stepID := r.PathValue("loginProcessID"), r.PathValue("stepID") owner, known := owners.owner(loginID) var input []byte var err error switch stepType := r.PathValue("stepType"); { case stepType != "user_input" && stepType != "cookies": err = fmt.Errorf("%w: only user_input and cookies steps take sealed input", loginseal.ErrMalformed) case !alone: err = fmt.Errorf("%w: other fields came with the sealed input", loginseal.ErrMalformed) case !known: err = errLoginUnknown case r.URL.Query().Get("user_id") != owner: err = errNotOwner default: // The app seals for its own user: input it sealed for one user opens for nobody else's login. if input, err = key.Open(loginseal.LoginInfo(k.network, owner, loginID, stepID), sealed); err == nil { err = stringFields(input) } } if err != nil { k.log.Warn().Err(err).Str("login_id", loginID).Str("step_id", stepID).Msg("Refused sealed sign-in input") switch { case errors.Is(err, errLoginUnknown): writeError(w, http.StatusNotFound, "M_NOT_FOUND", "Login not found") case errors.Is(err, errNotOwner): writeError(w, http.StatusForbidden, errLoginNotOwner, "The sign-in was started by another user") default: writeSealError(w, key, err) } return } opened := r.Clone(r.Context()) opened.Body = io.NopCloser(bytes.NewReader(input)) opened.ContentLength = int64(len(input)) opened.Header.Set("Content-Length", strconv.Itoa(len(input))) k.moveLogin(w, opened, router, key, owners) } // stringFields checks that opened input is what bridgev2 reads for user_input and cookies: one object // of strings. A null field would reach bridgev2 as an empty string. func stringFields(input []byte) error { var fields map[string]*string decoder := json.NewDecoder(bytes.NewReader(input)) if err := decoder.Decode(&fields); err != nil || fields == nil { return fmt.Errorf("%w: the sealed input is not an object of strings", loginseal.ErrMalformed) } for _, value := range fields { if value == nil { return fmt.Errorf("%w: a field of the sealed input is null", loginseal.ErrMalformed) } } if _, err := decoder.Token(); err != io.EOF { return fmt.Errorf("%w: data after the sealed input", loginseal.ErrMalformed) } return nil } // writeSealError answers a sealed value that did not open: sign-in input here, and the identity reset // proof, which opens with the same key. func writeSealError(w http.ResponseWriter, key *loginseal.Key, err error) { switch { case errors.Is(err, loginseal.ErrNoKey): writeError(w, http.StatusServiceUnavailable, errNoLoginKey, "The bridge has no login key") case errors.Is(err, loginseal.ErrKeyChanged): writeJSON(w, http.StatusPreconditionFailed, map[string]string{ "errcode": errLoginKeyChanged, "error": "Sealed to another login key; seal it to the attested one", "com.xessenger.login_kid": key.Kid(), }) case errors.Is(err, loginseal.ErrOpen): writeError(w, http.StatusBadRequest, errLoginOpen, "The sealed value does not open here") default: writeError(w, http.StatusBadRequest, errLoginEnvelope, err.Error()) } } // moveLogin hands a sign-in step on to the provisioning API and signs the step it answers for the user // who started the login. func (k *Kit) moveLogin(w http.ResponseWriter, r *http.Request, router *http.ServeMux, key *loginseal.Key, owners *loginOwners) { loginID := r.PathValue("loginProcessID") answer := askProvisioning(router, r) if owner, known := owners.owner(loginID); known { if _, stepType, ok := answeredStep(answer, loginID); ok { k.signStep(answer, key, owner) if stepType == "complete" { owners.forget(loginID) } } } answer.send(w) } // signStep adds the step an answer holds, signed for the user who started its login // (loginseal.SignedStepField). The answer is otherwise kept as bridgev2 wrote it. func (k *Kit) signStep(answer *bufferedAnswer, key *loginseal.Key, owner string) { if key == nil { return } step := bytes.TrimSpace(answer.body.Bytes()) var fields map[string]json.RawMessage if json.Unmarshal(step, &fields) != nil || len(fields) == 0 { return } if _, signed := fields[loginseal.SignedStepField]; signed { return } signed, err := key.SignStep(k.network, owner, step) var value []byte if err == nil { value, err = json.Marshal(signed) } if err != nil { k.log.Err(err).Msg("Failed to sign a sign-in step") return } // One more field at the end of the object, which has fields already. body := make([]byte, 0, len(step)+len(value)+len(loginseal.SignedStepField)+6) body = append(body, step[:len(step)-1]...) body = append(body, `,"`+loginseal.SignedStepField+`":`...) body = append(body, value...) body = append(body, "}\n"...) answer.body.Reset() answer.body.Write(body) } // provisioning is the provisioning API the routes here are in front of: the router's handler for the // same path under another method. func provisioning(router *http.ServeMux, r *http.Request) http.Handler { handler, pattern := router.Handler(&http.Request{Method: http.MethodGet, URL: r.URL, Host: r.Host}) if pattern == "" { // Only the routes here match: the provisioning API is not mounted (the bridge has not started, // or provisioning is disabled). return http.NotFoundHandler() } return handler } // askProvisioning has the provisioning API answer a request, the answer kept to sign the step in it. func askProvisioning(router *http.ServeMux, r *http.Request) *bufferedAnswer { answer := &bufferedAnswer{header: make(http.Header), status: http.StatusOK} provisioning(router, r).ServeHTTP(answer, r) return answer } // answeredStep reads the sign-in step in a provisioning answer, bridgev2's RespSubmitLogin: a JSON // object with the login process ID (loginID, when given) and the step's type. func answeredStep(answer *bufferedAnswer, loginID string) (string, string, bool) { contentType, _, _ := mime.ParseMediaType(answer.header.Get("Content-Type")) if answer.status != http.StatusOK || contentType != "application/json" { return "", "", false } var step struct { LoginID string `json:"login_id"` Type string `json:"type"` } if json.Unmarshal(answer.body.Bytes(), &step) != nil || step.LoginID == "" || step.Type == "" || (loginID != "" && step.LoginID != loginID) { return "", "", false } return step.LoginID, step.Type, true } // send writes the answer as it was kept, but for its length, which the body may have changed. func (b *bufferedAnswer) send(w http.ResponseWriter) { for key, values := range b.header { if key != "Content-Length" { w.Header()[key] = values } } w.WriteHeader(b.status) _, _ = w.Write(b.body.Bytes()) } // loginOwners remembers who started each login process, which bridgev2 does not tell. type loginOwners struct { lock sync.Mutex owners map[string]loginStart now func() time.Time } // loginStart is who started a login process, and when. type loginStart struct { userID string started time.Time } func newLoginOwners() *loginOwners { return &loginOwners{owners: make(map[string]loginStart), now: time.Now} } // remember keeps the user who started a login process, dropping those bridgev2 gave up. func (o *loginOwners) remember(loginID, userID string) { o.lock.Lock() defer o.lock.Unlock() now := o.now() for id, owner := range o.owners { if now.Sub(owner.started) > loginOwnerTTL { delete(o.owners, id) } } o.owners[loginID] = loginStart{userID: userID, started: now} } func (o *loginOwners) owner(loginID string) (string, bool) { o.lock.Lock() defer o.lock.Unlock() owner, ok := o.owners[loginID] if !ok || o.now().Sub(owner.started) > loginOwnerTTL { return "", false } return owner.userID, true } func (o *loginOwners) forget(loginID string) { o.lock.Lock() defer o.lock.Unlock() delete(o.owners, loginID) }