2022-02-21 16:12:22 +00:00
|
|
|
// Copyright 2022 The Matrix.org Foundation C.I.C.
|
|
|
|
//
|
|
|
|
// 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-07-01 09:49:26 +00:00
|
|
|
"context"
|
2022-02-21 16:12:22 +00:00
|
|
|
"database/sql"
|
|
|
|
"encoding/json"
|
2022-03-03 17:58:24 +00:00
|
|
|
"fmt"
|
2022-02-21 16:12:22 +00:00
|
|
|
"net/http"
|
|
|
|
"strconv"
|
2022-08-11 16:23:35 +00:00
|
|
|
"time"
|
2022-02-21 16:12:22 +00:00
|
|
|
|
|
|
|
"github.com/matrix-org/dendrite/clientapi/jsonerror"
|
2022-04-22 09:38:29 +00:00
|
|
|
"github.com/matrix-org/dendrite/internal/caching"
|
2022-02-21 16:12:22 +00:00
|
|
|
roomserver "github.com/matrix-org/dendrite/roomserver/api"
|
2022-08-11 16:23:35 +00:00
|
|
|
"github.com/matrix-org/dendrite/syncapi/internal"
|
2022-02-21 16:12:22 +00:00
|
|
|
"github.com/matrix-org/dendrite/syncapi/storage"
|
2022-07-01 09:49:26 +00:00
|
|
|
"github.com/matrix-org/dendrite/syncapi/types"
|
2022-02-21 16:12:22 +00:00
|
|
|
userapi "github.com/matrix-org/dendrite/userapi/api"
|
|
|
|
"github.com/matrix-org/gomatrixserverlib"
|
|
|
|
"github.com/matrix-org/util"
|
|
|
|
"github.com/sirupsen/logrus"
|
|
|
|
)
|
|
|
|
|
|
|
|
type ContextRespsonse struct {
|
|
|
|
End string `json:"end"`
|
2022-09-27 16:06:49 +00:00
|
|
|
Event *gomatrixserverlib.ClientEvent `json:"event,omitempty"`
|
2022-02-21 16:12:22 +00:00
|
|
|
EventsAfter []gomatrixserverlib.ClientEvent `json:"events_after,omitempty"`
|
|
|
|
EventsBefore []gomatrixserverlib.ClientEvent `json:"events_before,omitempty"`
|
|
|
|
Start string `json:"start"`
|
2022-09-27 16:06:49 +00:00
|
|
|
State []gomatrixserverlib.ClientEvent `json:"state,omitempty"`
|
2022-02-21 16:12:22 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func Context(
|
|
|
|
req *http.Request, device *userapi.Device,
|
2022-05-05 08:56:03 +00:00
|
|
|
rsAPI roomserver.SyncRoomserverAPI,
|
2022-02-21 16:12:22 +00:00
|
|
|
syncDB storage.Database,
|
|
|
|
roomID, eventID string,
|
2022-05-06 13:33:34 +00:00
|
|
|
lazyLoadCache caching.LazyLoadCache,
|
2022-02-21 16:12:22 +00:00
|
|
|
) util.JSONResponse {
|
2022-09-30 11:48:10 +00:00
|
|
|
snapshot, err := syncDB.NewDatabaseSnapshot(req.Context())
|
|
|
|
if err != nil {
|
|
|
|
return jsonerror.InternalServerError()
|
|
|
|
}
|
|
|
|
defer snapshot.Rollback() // nolint:errcheck
|
|
|
|
|
2022-03-01 14:39:56 +00:00
|
|
|
filter, err := parseRoomEventFilter(req)
|
2022-02-21 16:12:22 +00:00
|
|
|
if err != nil {
|
|
|
|
errMsg := ""
|
|
|
|
switch err.(type) {
|
|
|
|
case *json.InvalidUnmarshalError:
|
|
|
|
errMsg = "unable to parse filter"
|
|
|
|
case *strconv.NumError:
|
|
|
|
errMsg = "unable to parse limit"
|
|
|
|
}
|
|
|
|
return util.JSONResponse{
|
|
|
|
Code: http.StatusBadRequest,
|
|
|
|
JSON: jsonerror.InvalidParam(errMsg),
|
|
|
|
Headers: nil,
|
|
|
|
}
|
|
|
|
}
|
2022-04-11 07:05:23 +00:00
|
|
|
if filter.Rooms != nil {
|
|
|
|
*filter.Rooms = append(*filter.Rooms, roomID)
|
|
|
|
}
|
2022-02-21 16:12:22 +00:00
|
|
|
|
|
|
|
ctx := req.Context()
|
|
|
|
membershipRes := roomserver.QueryMembershipForUserResponse{}
|
|
|
|
membershipReq := roomserver.QueryMembershipForUserRequest{UserID: device.UserID, RoomID: roomID}
|
2022-02-21 16:38:53 +00:00
|
|
|
if err = rsAPI.QueryMembershipForUser(ctx, &membershipReq, &membershipRes); err != nil {
|
2022-03-14 19:04:24 +00:00
|
|
|
logrus.WithError(err).Error("unable to query membership")
|
2022-02-21 16:12:22 +00:00
|
|
|
return jsonerror.InternalServerError()
|
|
|
|
}
|
2022-05-11 10:29:23 +00:00
|
|
|
if !membershipRes.RoomExists {
|
|
|
|
return util.JSONResponse{
|
|
|
|
Code: http.StatusForbidden,
|
|
|
|
JSON: jsonerror.Forbidden("room does not exist"),
|
|
|
|
}
|
|
|
|
}
|
2022-02-21 16:12:22 +00:00
|
|
|
|
|
|
|
stateFilter := gomatrixserverlib.StateFilter{
|
|
|
|
Limit: 100,
|
|
|
|
NotSenders: filter.NotSenders,
|
|
|
|
NotTypes: filter.NotTypes,
|
|
|
|
Senders: filter.Senders,
|
|
|
|
Types: filter.Types,
|
|
|
|
LazyLoadMembers: filter.LazyLoadMembers,
|
|
|
|
IncludeRedundantMembers: filter.IncludeRedundantMembers,
|
|
|
|
NotRooms: filter.NotRooms,
|
|
|
|
Rooms: filter.Rooms,
|
|
|
|
ContainsURL: filter.ContainsURL,
|
|
|
|
}
|
|
|
|
|
2022-09-30 11:48:10 +00:00
|
|
|
id, requestedEvent, err := snapshot.SelectContextEvent(ctx, roomID, eventID)
|
2022-02-21 16:12:22 +00:00
|
|
|
if err != nil {
|
2022-03-03 17:58:24 +00:00
|
|
|
if err == sql.ErrNoRows {
|
|
|
|
return util.JSONResponse{
|
|
|
|
Code: http.StatusNotFound,
|
|
|
|
JSON: jsonerror.NotFound(fmt.Sprintf("Event %s not found", eventID)),
|
|
|
|
}
|
|
|
|
}
|
2022-02-21 16:12:22 +00:00
|
|
|
logrus.WithError(err).WithField("eventID", eventID).Error("unable to find requested event")
|
|
|
|
return jsonerror.InternalServerError()
|
|
|
|
}
|
|
|
|
|
2022-08-11 16:23:35 +00:00
|
|
|
// verify the user is allowed to see the context for this room/event
|
|
|
|
startTime := time.Now()
|
2022-09-30 11:48:10 +00:00
|
|
|
filteredEvents, err := internal.ApplyHistoryVisibilityFilter(ctx, snapshot, rsAPI, []*gomatrixserverlib.HeaderedEvent{&requestedEvent}, nil, device.UserID, "context")
|
2022-08-11 16:23:35 +00:00
|
|
|
if err != nil {
|
|
|
|
logrus.WithError(err).Error("unable to apply history visibility filter")
|
|
|
|
return jsonerror.InternalServerError()
|
|
|
|
}
|
|
|
|
logrus.WithFields(logrus.Fields{
|
|
|
|
"duration": time.Since(startTime),
|
|
|
|
"room_id": roomID,
|
|
|
|
}).Debug("applied history visibility (context)")
|
|
|
|
if len(filteredEvents) == 0 {
|
|
|
|
return util.JSONResponse{
|
|
|
|
Code: http.StatusForbidden,
|
|
|
|
JSON: jsonerror.Forbidden("User is not allowed to query context"),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-09-30 11:48:10 +00:00
|
|
|
eventsBefore, err := snapshot.SelectContextBeforeEvent(ctx, id, roomID, filter)
|
2022-02-21 16:12:22 +00:00
|
|
|
if err != nil && err != sql.ErrNoRows {
|
|
|
|
logrus.WithError(err).Error("unable to fetch before events")
|
|
|
|
return jsonerror.InternalServerError()
|
|
|
|
}
|
|
|
|
|
2022-09-30 11:48:10 +00:00
|
|
|
_, eventsAfter, err := snapshot.SelectContextAfterEvent(ctx, id, roomID, filter)
|
2022-02-21 16:12:22 +00:00
|
|
|
if err != nil && err != sql.ErrNoRows {
|
|
|
|
logrus.WithError(err).Error("unable to fetch after events")
|
|
|
|
return jsonerror.InternalServerError()
|
|
|
|
}
|
|
|
|
|
2022-08-11 16:23:35 +00:00
|
|
|
startTime = time.Now()
|
2022-09-30 11:48:10 +00:00
|
|
|
eventsBeforeFiltered, eventsAfterFiltered, err := applyHistoryVisibilityOnContextEvents(ctx, snapshot, rsAPI, eventsBefore, eventsAfter, device.UserID)
|
2022-08-11 16:23:35 +00:00
|
|
|
if err != nil {
|
|
|
|
logrus.WithError(err).Error("unable to apply history visibility filter")
|
|
|
|
return jsonerror.InternalServerError()
|
|
|
|
}
|
|
|
|
|
|
|
|
logrus.WithFields(logrus.Fields{
|
|
|
|
"duration": time.Since(startTime),
|
|
|
|
"room_id": roomID,
|
|
|
|
}).Debug("applied history visibility (context eventsBefore/eventsAfter)")
|
|
|
|
|
|
|
|
// TODO: Get the actual state at the last event returned by SelectContextAfterEvent
|
2022-09-30 11:48:10 +00:00
|
|
|
state, err := snapshot.CurrentState(ctx, roomID, &stateFilter, nil)
|
2022-08-11 16:23:35 +00:00
|
|
|
if err != nil {
|
|
|
|
logrus.WithError(err).Error("unable to fetch current room state")
|
|
|
|
return jsonerror.InternalServerError()
|
|
|
|
}
|
|
|
|
|
|
|
|
eventsBeforeClient := gomatrixserverlib.HeaderedToClientEvents(eventsBeforeFiltered, gomatrixserverlib.FormatAll)
|
|
|
|
eventsAfterClient := gomatrixserverlib.HeaderedToClientEvents(eventsAfterFiltered, gomatrixserverlib.FormatAll)
|
2022-04-22 09:38:29 +00:00
|
|
|
newState := applyLazyLoadMembers(device, filter, eventsAfterClient, eventsBeforeClient, state, lazyLoadCache)
|
2022-02-21 16:12:22 +00:00
|
|
|
|
2022-09-27 16:06:49 +00:00
|
|
|
ev := gomatrixserverlib.HeaderedToClientEvent(&requestedEvent, gomatrixserverlib.FormatAll)
|
2022-02-21 16:12:22 +00:00
|
|
|
response := ContextRespsonse{
|
2022-09-27 16:06:49 +00:00
|
|
|
Event: &ev,
|
2022-02-21 16:12:22 +00:00
|
|
|
EventsAfter: eventsAfterClient,
|
|
|
|
EventsBefore: eventsBeforeClient,
|
|
|
|
State: gomatrixserverlib.HeaderedToClientEvents(newState, gomatrixserverlib.FormatAll),
|
|
|
|
}
|
|
|
|
|
|
|
|
if len(response.State) > filter.Limit {
|
|
|
|
response.State = response.State[len(response.State)-filter.Limit:]
|
|
|
|
}
|
2022-09-30 11:48:10 +00:00
|
|
|
start, end, err := getStartEnd(ctx, snapshot, eventsBefore, eventsAfter)
|
2022-07-01 09:49:26 +00:00
|
|
|
if err == nil {
|
|
|
|
response.End = end.String()
|
|
|
|
response.Start = start.String()
|
|
|
|
}
|
2022-02-21 16:12:22 +00:00
|
|
|
return util.JSONResponse{
|
|
|
|
Code: http.StatusOK,
|
|
|
|
JSON: response,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-08-11 16:23:35 +00:00
|
|
|
// applyHistoryVisibilityOnContextEvents is a helper function to avoid roundtrips to the roomserver
|
|
|
|
// by combining the events before and after the context event. Returns the filtered events,
|
|
|
|
// and an error, if any.
|
|
|
|
func applyHistoryVisibilityOnContextEvents(
|
2022-09-30 11:48:10 +00:00
|
|
|
ctx context.Context, snapshot storage.DatabaseTransaction, rsAPI roomserver.SyncRoomserverAPI,
|
2022-08-11 16:23:35 +00:00
|
|
|
eventsBefore, eventsAfter []*gomatrixserverlib.HeaderedEvent,
|
|
|
|
userID string,
|
|
|
|
) (filteredBefore, filteredAfter []*gomatrixserverlib.HeaderedEvent, err error) {
|
|
|
|
eventIDsBefore := make(map[string]struct{}, len(eventsBefore))
|
|
|
|
eventIDsAfter := make(map[string]struct{}, len(eventsAfter))
|
|
|
|
|
|
|
|
// Remember before/after eventIDs, so we can restore them
|
|
|
|
// after applying history visibility checks
|
|
|
|
for _, ev := range eventsBefore {
|
|
|
|
eventIDsBefore[ev.EventID()] = struct{}{}
|
|
|
|
}
|
|
|
|
for _, ev := range eventsAfter {
|
|
|
|
eventIDsAfter[ev.EventID()] = struct{}{}
|
|
|
|
}
|
|
|
|
|
|
|
|
allEvents := append(eventsBefore, eventsAfter...)
|
2022-09-30 11:48:10 +00:00
|
|
|
filteredEvents, err := internal.ApplyHistoryVisibilityFilter(ctx, snapshot, rsAPI, allEvents, nil, userID, "context")
|
2022-08-11 16:23:35 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
// "Restore" events in the correct context
|
|
|
|
for _, ev := range filteredEvents {
|
|
|
|
if _, ok := eventIDsBefore[ev.EventID()]; ok {
|
|
|
|
filteredBefore = append(filteredBefore, ev)
|
|
|
|
}
|
|
|
|
if _, ok := eventIDsAfter[ev.EventID()]; ok {
|
|
|
|
filteredAfter = append(filteredAfter, ev)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return filteredBefore, filteredAfter, nil
|
|
|
|
}
|
|
|
|
|
2022-09-30 11:48:10 +00:00
|
|
|
func getStartEnd(ctx context.Context, snapshot storage.DatabaseTransaction, startEvents, endEvents []*gomatrixserverlib.HeaderedEvent) (start, end types.TopologyToken, err error) {
|
2022-07-01 09:49:26 +00:00
|
|
|
if len(startEvents) > 0 {
|
2022-09-30 11:48:10 +00:00
|
|
|
start, err = snapshot.EventPositionInTopology(ctx, startEvents[0].EventID())
|
2022-07-01 09:49:26 +00:00
|
|
|
if err != nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if len(endEvents) > 0 {
|
2022-09-30 11:48:10 +00:00
|
|
|
end, err = snapshot.EventPositionInTopology(ctx, endEvents[0].EventID())
|
2022-07-01 09:49:26 +00:00
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2022-04-22 09:38:29 +00:00
|
|
|
func applyLazyLoadMembers(
|
|
|
|
device *userapi.Device,
|
|
|
|
filter *gomatrixserverlib.RoomEventFilter,
|
|
|
|
eventsAfter, eventsBefore []gomatrixserverlib.ClientEvent,
|
|
|
|
state []*gomatrixserverlib.HeaderedEvent,
|
2022-05-06 13:33:34 +00:00
|
|
|
lazyLoadCache caching.LazyLoadCache,
|
2022-04-22 09:38:29 +00:00
|
|
|
) []*gomatrixserverlib.HeaderedEvent {
|
2022-02-21 16:12:22 +00:00
|
|
|
if filter == nil || !filter.LazyLoadMembers {
|
|
|
|
return state
|
|
|
|
}
|
|
|
|
allEvents := append(eventsBefore, eventsAfter...)
|
2022-04-22 09:38:29 +00:00
|
|
|
x := make(map[string]struct{})
|
2022-02-21 16:12:22 +00:00
|
|
|
// get members who actually send an event
|
|
|
|
for _, e := range allEvents {
|
2022-04-22 09:38:29 +00:00
|
|
|
// Don't add membership events the client should already know about
|
|
|
|
if _, cached := lazyLoadCache.IsLazyLoadedUserCached(device, e.RoomID, e.Sender); cached {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
x[e.Sender] = struct{}{}
|
2022-02-21 16:12:22 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
newState := []*gomatrixserverlib.HeaderedEvent{}
|
2022-03-14 19:04:24 +00:00
|
|
|
membershipEvents := []*gomatrixserverlib.HeaderedEvent{}
|
2022-02-21 16:12:22 +00:00
|
|
|
for _, event := range state {
|
|
|
|
if event.Type() != gomatrixserverlib.MRoomMember {
|
|
|
|
newState = append(newState, event)
|
|
|
|
} else {
|
|
|
|
// did the user send an event?
|
2022-04-22 09:38:29 +00:00
|
|
|
if _, ok := x[event.Sender()]; ok {
|
2022-03-14 19:04:24 +00:00
|
|
|
membershipEvents = append(membershipEvents, event)
|
2022-04-22 09:38:29 +00:00
|
|
|
lazyLoadCache.StoreLazyLoadedUser(device, event.RoomID(), event.Sender(), event.EventID())
|
2022-02-21 16:12:22 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2022-03-14 19:04:24 +00:00
|
|
|
// Add the membershipEvents to the end of the list, to make Sytest happy
|
|
|
|
return append(newState, membershipEvents...)
|
2022-02-21 16:12:22 +00:00
|
|
|
}
|
|
|
|
|
2022-03-01 14:39:56 +00:00
|
|
|
func parseRoomEventFilter(req *http.Request) (*gomatrixserverlib.RoomEventFilter, error) {
|
2022-02-21 16:12:22 +00:00
|
|
|
// Default room filter
|
|
|
|
filter := &gomatrixserverlib.RoomEventFilter{Limit: 10}
|
|
|
|
|
|
|
|
l := req.URL.Query().Get("limit")
|
|
|
|
f := req.URL.Query().Get("filter")
|
|
|
|
if l != "" {
|
|
|
|
limit, err := strconv.Atoi(l)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
// NOTSPEC: feels like a good idea to have an upper bound limit
|
|
|
|
if limit > 100 {
|
|
|
|
limit = 100
|
|
|
|
}
|
|
|
|
filter.Limit = limit
|
|
|
|
}
|
|
|
|
if f != "" {
|
|
|
|
if err := json.Unmarshal([]byte(f), &filter); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return filter, nil
|
|
|
|
}
|