dendrite/federationapi/routing/leave.go

267 lines
8.7 KiB
Go
Raw Normal View History

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package routing
import (
2022-11-15 09:05:23 -06:00
"fmt"
"net/http"
"time"
"github.com/matrix-org/dendrite/internal/eventutil"
"github.com/matrix-org/dendrite/roomserver/api"
"github.com/matrix-org/dendrite/roomserver/types"
"github.com/matrix-org/dendrite/setup/config"
"github.com/matrix-org/gomatrixserverlib"
"github.com/matrix-org/gomatrixserverlib/fclient"
"github.com/matrix-org/gomatrixserverlib/spec"
"github.com/matrix-org/util"
"github.com/sirupsen/logrus"
)
// MakeLeave implements the /make_leave API
func MakeLeave(
httpReq *http.Request,
request *fclient.FederationRequest,
cfg *config.FederationAPI,
rsAPI api.FederationRoomserverAPI,
roomID spec.RoomID, userID spec.UserID,
) util.JSONResponse {
roomVersion, err := rsAPI.QueryRoomVersionForRoom(httpReq.Context(), roomID.String())
if err != nil {
util.GetLogger(httpReq.Context()).WithError(err).Error("failed obtaining room version")
return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
}
req := api.QueryServerJoinedToRoomRequest{
ServerName: request.Destination(),
RoomID: roomID.String(),
}
res := api.QueryServerJoinedToRoomResponse{}
2023-06-07 12:14:35 -05:00
if err = rsAPI.QueryServerJoinedToRoom(httpReq.Context(), &req, &res); err != nil {
util.GetLogger(httpReq.Context()).WithError(err).Error("rsAPI.QueryServerJoinedToRoom failed")
2023-05-16 19:33:27 -05:00
return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
}
createLeaveTemplate := func(proto *gomatrixserverlib.ProtoEvent) (gomatrixserverlib.PDU, []gomatrixserverlib.PDU, error) {
2023-06-07 12:14:35 -05:00
identity, signErr := cfg.Matrix.SigningIdentityFor(request.Destination())
if signErr != nil {
util.GetLogger(httpReq.Context()).WithError(signErr).Errorf("obtaining signing identity for %s failed", request.Destination())
return nil, nil, spec.NotFound(fmt.Sprintf("Server name %q does not exist", request.Destination()))
2022-11-15 09:05:23 -06:00
}
queryRes := api.QueryLatestEventsAndStateResponse{}
2023-06-07 12:14:35 -05:00
event, buildErr := eventutil.QueryAndBuildEvent(httpReq.Context(), proto, identity, time.Now(), rsAPI, &queryRes)
switch e := buildErr.(type) {
case nil:
case eventutil.ErrRoomNoExists:
2023-06-07 12:14:35 -05:00
util.GetLogger(httpReq.Context()).WithError(buildErr).Error("eventutil.BuildEvent failed")
return nil, nil, spec.NotFound("Room does not exist")
case gomatrixserverlib.BadJSONError:
2023-06-07 12:14:35 -05:00
util.GetLogger(httpReq.Context()).WithError(buildErr).Error("eventutil.BuildEvent failed")
return nil, nil, spec.BadJSON(e.Error())
default:
2023-06-07 12:14:35 -05:00
util.GetLogger(httpReq.Context()).WithError(buildErr).Error("eventutil.BuildEvent failed")
return nil, nil, spec.InternalServerError{}
}
stateEvents := make([]gomatrixserverlib.PDU, len(queryRes.StateEvents))
for i, stateEvent := range queryRes.StateEvents {
stateEvents[i] = stateEvent.PDU
}
return event, stateEvents, nil
}
senderID, err := rsAPI.QuerySenderIDForUser(httpReq.Context(), roomID, userID)
2023-06-07 12:14:35 -05:00
if err != nil {
util.GetLogger(httpReq.Context()).WithError(err).Error("rsAPI.QuerySenderIDForUser failed")
return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
} else if senderID == nil {
util.GetLogger(httpReq.Context()).WithField("roomID", roomID).WithField("userID", userID).Error("rsAPI.QuerySenderIDForUser returned nil sender ID")
return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
2023-06-07 12:14:35 -05:00
}
input := gomatrixserverlib.HandleMakeLeaveInput{
UserID: userID,
SenderID: *senderID,
RoomID: roomID,
RoomVersion: roomVersion,
RequestOrigin: request.Origin(),
LocalServerName: cfg.Matrix.ServerName,
LocalServerInRoom: res.RoomExists && res.IsInRoom,
BuildEventTemplate: createLeaveTemplate,
UserIDQuerier: func(roomID spec.RoomID, senderID spec.SenderID) (*spec.UserID, error) {
return rsAPI.QueryUserIDForSender(httpReq.Context(), roomID, senderID)
},
}
response, internalErr := gomatrixserverlib.HandleMakeLeave(input)
switch e := internalErr.(type) {
case nil:
case spec.InternalServerError:
util.GetLogger(httpReq.Context()).WithError(internalErr).Error("failed to handle make_leave request")
2023-05-16 19:33:27 -05:00
return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
case spec.MatrixError:
util.GetLogger(httpReq.Context()).WithError(internalErr).Error("failed to handle make_leave request")
code := http.StatusInternalServerError
switch e.ErrCode {
case spec.ErrorForbidden:
code = http.StatusForbidden
case spec.ErrorNotFound:
code = http.StatusNotFound
case spec.ErrorBadJSON:
code = http.StatusBadRequest
}
return util.JSONResponse{
Code: code,
JSON: e,
}
default:
util.GetLogger(httpReq.Context()).WithError(internalErr).Error("failed to handle make_leave request")
return util.JSONResponse{
Code: http.StatusBadRequest,
JSON: spec.Unknown("unknown error"),
}
}
if response == nil {
util.GetLogger(httpReq.Context()).Error("gmsl.HandleMakeLeave returned invalid response")
return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
}
return util.JSONResponse{
Code: http.StatusOK,
JSON: map[string]interface{}{
"event": response.LeaveTemplateEvent,
"room_version": response.RoomVersion,
},
}
}
// SendLeave implements the /send_leave API
// nolint:gocyclo
func SendLeave(
httpReq *http.Request,
request *fclient.FederationRequest,
cfg *config.FederationAPI,
rsAPI api.FederationRoomserverAPI,
keys gomatrixserverlib.JSONVerifier,
roomID, eventID string,
) util.JSONResponse {
roomVersion, err := rsAPI.QueryRoomVersionForRoom(httpReq.Context(), roomID)
if err != nil {
Further room version wiring (#936) * Room version 2 by default, other wiring updates, update gomatrixserverlib * Fix nil pointer exception * Fix some more nil pointer exceptions hopefully * Update gomatrixserverlib * Send all room versions when joining, not just stable ones * Remove room version cquery * Get room version when getting events from the roomserver database * Reset default back to room version 2 * Don't generate event IDs unless needed * Revert "Remove room version cquery" This reverts commit a170d5873360dd059614460acc8b21ab2cda9767. * Query room version in federation API, client API as needed * Improvements to make_join send_join dance * Make room server producers use headered events * Lint tweaks * Update gomatrixserverlib * Versioned SendJoin * Query room version in syncapi backfill * Handle transaction marshalling/unmarshalling within Dendrite * Sorta fix federation (kinda) * whoops commit federation API too * Use NewEventFromTrustedJSON when getting events from the database * Update gomatrixserverlib * Strip headers on federationapi endpoints * Fix bug in clientapi profile room version query * Update gomatrixserverlib * Return more useful error if room version query doesn't find the room * Update gomatrixserverlib * Update gomatrixserverlib * Maybe fix federation * Fix formatting directive * Update sytest whitelist and blacklist * Temporarily disable room versions 3 and 4 until gmsl is fixed * Fix count of EDUs in logging * Update gomatrixserverlib * Update gomatrixserverlib * Update gomatrixserverlib * Rely on EventBuilder in gmsl to generate the event IDs for us * Some review comments fixed * Move function out of common and into gmsl * Comment in federationsender destinationqueue * Update gomatrixserverlib
2020-03-27 11:28:22 -05:00
return util.JSONResponse{
Code: http.StatusBadRequest,
2023-05-09 17:46:49 -05:00
JSON: spec.UnsupportedRoomVersion(err.Error()),
Further room version wiring (#936) * Room version 2 by default, other wiring updates, update gomatrixserverlib * Fix nil pointer exception * Fix some more nil pointer exceptions hopefully * Update gomatrixserverlib * Send all room versions when joining, not just stable ones * Remove room version cquery * Get room version when getting events from the roomserver database * Reset default back to room version 2 * Don't generate event IDs unless needed * Revert "Remove room version cquery" This reverts commit a170d5873360dd059614460acc8b21ab2cda9767. * Query room version in federation API, client API as needed * Improvements to make_join send_join dance * Make room server producers use headered events * Lint tweaks * Update gomatrixserverlib * Versioned SendJoin * Query room version in syncapi backfill * Handle transaction marshalling/unmarshalling within Dendrite * Sorta fix federation (kinda) * whoops commit federation API too * Use NewEventFromTrustedJSON when getting events from the database * Update gomatrixserverlib * Strip headers on federationapi endpoints * Fix bug in clientapi profile room version query * Update gomatrixserverlib * Return more useful error if room version query doesn't find the room * Update gomatrixserverlib * Update gomatrixserverlib * Maybe fix federation * Fix formatting directive * Update sytest whitelist and blacklist * Temporarily disable room versions 3 and 4 until gmsl is fixed * Fix count of EDUs in logging * Update gomatrixserverlib * Update gomatrixserverlib * Update gomatrixserverlib * Rely on EventBuilder in gmsl to generate the event IDs for us * Some review comments fixed * Move function out of common and into gmsl * Comment in federationsender destinationqueue * Update gomatrixserverlib
2020-03-27 11:28:22 -05:00
}
}
2023-11-23 04:26:23 -06:00
leaveEvent, err := gomatrixserverlib.HandleSendLeave(
2023-11-23 05:21:01 -06:00
httpReq.Context(), request.Content(), request.Origin(), roomVersion, eventID, roomID, rsAPI, keys)
2023-05-24 12:18:18 -05:00
switch e := err.(type) {
case nil:
2023-05-24 12:18:18 -05:00
case spec.InternalServerError:
util.GetLogger(httpReq.Context()).WithError(err).Error("failed to handle send_leave request")
2023-05-16 19:33:27 -05:00
return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
2023-05-24 12:18:18 -05:00
case spec.MatrixError:
util.GetLogger(httpReq.Context()).WithError(err).Error("failed to handle send_leave request")
code := http.StatusInternalServerError
switch e.ErrCode {
case spec.ErrorForbidden:
code = http.StatusForbidden
case spec.ErrorNotFound:
code = http.StatusNotFound
case spec.ErrorUnsupportedRoomVersion:
code = http.StatusInternalServerError
case spec.ErrorBadJSON:
code = http.StatusBadRequest
}
return util.JSONResponse{
2023-05-24 12:18:18 -05:00
Code: code,
JSON: e,
}
2023-05-24 12:18:18 -05:00
default:
util.GetLogger(httpReq.Context()).WithError(err).Error("failed to handle send_leave request")
return util.JSONResponse{
Code: http.StatusBadRequest,
2023-05-24 12:18:18 -05:00
JSON: spec.Unknown("unknown error"),
}
}
2023-11-23 05:21:01 -06:00
// The user was never joined to the room, has already left,
// or we already processed this leave event, so this is a no-op.
if leaveEvent == nil {
return util.JSONResponse{
Code: http.StatusOK,
JSON: struct{}{},
}
}
// Send the events to the room server.
// We are responsible for notifying other servers that the user has left
// the room, so set SendAsServer to cfg.Matrix.ServerName
var response api.InputRoomEventsResponse
2023-05-09 17:46:49 -05:00
rsAPI.InputRoomEvents(httpReq.Context(), &api.InputRoomEventsRequest{
InputRoomEvents: []api.InputRoomEvent{
{
Kind: api.KindNew,
Event: &types.HeaderedEvent{PDU: leaveEvent},
SendAsServer: string(cfg.Matrix.ServerName),
TransactionID: nil,
},
Further room version wiring (#936) * Room version 2 by default, other wiring updates, update gomatrixserverlib * Fix nil pointer exception * Fix some more nil pointer exceptions hopefully * Update gomatrixserverlib * Send all room versions when joining, not just stable ones * Remove room version cquery * Get room version when getting events from the roomserver database * Reset default back to room version 2 * Don't generate event IDs unless needed * Revert "Remove room version cquery" This reverts commit a170d5873360dd059614460acc8b21ab2cda9767. * Query room version in federation API, client API as needed * Improvements to make_join send_join dance * Make room server producers use headered events * Lint tweaks * Update gomatrixserverlib * Versioned SendJoin * Query room version in syncapi backfill * Handle transaction marshalling/unmarshalling within Dendrite * Sorta fix federation (kinda) * whoops commit federation API too * Use NewEventFromTrustedJSON when getting events from the database * Update gomatrixserverlib * Strip headers on federationapi endpoints * Fix bug in clientapi profile room version query * Update gomatrixserverlib * Return more useful error if room version query doesn't find the room * Update gomatrixserverlib * Update gomatrixserverlib * Maybe fix federation * Fix formatting directive * Update sytest whitelist and blacklist * Temporarily disable room versions 3 and 4 until gmsl is fixed * Fix count of EDUs in logging * Update gomatrixserverlib * Update gomatrixserverlib * Update gomatrixserverlib * Rely on EventBuilder in gmsl to generate the event IDs for us * Some review comments fixed * Move function out of common and into gmsl * Comment in federationsender destinationqueue * Update gomatrixserverlib
2020-03-27 11:28:22 -05:00
},
2023-05-09 17:46:49 -05:00
}, &response)
if response.ErrMsg != "" {
util.GetLogger(httpReq.Context()).WithField(logrus.ErrorKey, response.ErrMsg).WithField("not_allowed", response.NotAllowed).Error("producer.SendEvents failed")
if response.NotAllowed {
return util.JSONResponse{
Code: http.StatusBadRequest,
2023-05-09 17:46:49 -05:00
JSON: spec.Forbidden(response.ErrMsg),
}
}
2023-05-16 19:33:27 -05:00
return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: spec.InternalServerError{},
}
}
return util.JSONResponse{
Code: http.StatusOK,
JSON: struct{}{},
}
}