2017-04-21 00:40:52 +02:00
|
|
|
// Copyright 2017 Vector Creations Ltd
|
2020-02-05 19:06:39 +01:00
|
|
|
// Copyright 2018 New Vector Ltd
|
|
|
|
// Copyright 2019-2020 The Matrix.org Foundation C.I.C.
|
2017-04-21 00:40:52 +02:00
|
|
|
//
|
|
|
|
// 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.
|
|
|
|
|
2020-09-02 18:13:15 +02:00
|
|
|
package input
|
2017-02-07 18:20:05 +01:00
|
|
|
|
|
|
|
import (
|
2020-10-20 12:42:54 +02:00
|
|
|
"bytes"
|
2017-09-13 17:30:19 +02:00
|
|
|
"context"
|
2020-07-21 16:48:21 +02:00
|
|
|
"fmt"
|
2021-01-13 18:31:46 +01:00
|
|
|
"time"
|
2017-08-21 17:37:11 +02:00
|
|
|
|
2022-01-27 15:29:14 +01:00
|
|
|
fedapi "github.com/matrix-org/dendrite/federationapi/api"
|
|
|
|
"github.com/matrix-org/dendrite/internal"
|
2020-07-07 13:51:55 +02:00
|
|
|
"github.com/matrix-org/dendrite/internal/eventutil"
|
2022-01-28 13:33:31 +01:00
|
|
|
"github.com/matrix-org/dendrite/internal/hooks"
|
2022-02-23 16:41:32 +01:00
|
|
|
"github.com/matrix-org/dendrite/internal/sqlutil"
|
2017-02-07 18:20:05 +01:00
|
|
|
"github.com/matrix-org/dendrite/roomserver/api"
|
2020-09-02 14:47:31 +02:00
|
|
|
"github.com/matrix-org/dendrite/roomserver/internal/helpers"
|
2017-03-08 16:10:26 +01:00
|
|
|
"github.com/matrix-org/dendrite/roomserver/state"
|
2017-02-09 17:48:14 +01:00
|
|
|
"github.com/matrix-org/dendrite/roomserver/types"
|
2017-02-07 18:20:05 +01:00
|
|
|
"github.com/matrix-org/gomatrixserverlib"
|
2020-10-20 12:42:54 +02:00
|
|
|
"github.com/matrix-org/util"
|
2022-06-07 15:23:26 +02:00
|
|
|
"github.com/opentracing/opentracing-go"
|
2021-01-13 18:31:46 +01:00
|
|
|
"github.com/prometheus/client_golang/prometheus"
|
2020-04-28 12:46:47 +02:00
|
|
|
"github.com/sirupsen/logrus"
|
2017-02-07 18:20:05 +01:00
|
|
|
)
|
|
|
|
|
2022-01-27 15:29:14 +01:00
|
|
|
// TODO: Does this value make sense?
|
2022-01-31 11:39:33 +01:00
|
|
|
const MaximumMissingProcessingTime = time.Minute * 2
|
2022-01-27 15:29:14 +01:00
|
|
|
|
2021-01-13 18:31:46 +01:00
|
|
|
var processRoomEventDuration = prometheus.NewHistogramVec(
|
|
|
|
prometheus.HistogramOpts{
|
|
|
|
Namespace: "dendrite",
|
|
|
|
Subsystem: "roomserver",
|
|
|
|
Name: "processroomevent_duration_millis",
|
|
|
|
Help: "How long it takes the roomserver to process an event",
|
|
|
|
Buckets: []float64{ // milliseconds
|
|
|
|
5, 10, 25, 50, 75, 100, 250, 500,
|
|
|
|
1000, 2000, 3000, 4000, 5000, 6000,
|
|
|
|
7000, 8000, 9000, 10000, 15000, 20000,
|
|
|
|
},
|
|
|
|
},
|
|
|
|
[]string{"room_id"},
|
|
|
|
)
|
|
|
|
|
2017-12-15 16:22:06 +01:00
|
|
|
// processRoomEvent can only be called once at a time
|
|
|
|
//
|
|
|
|
// TODO(#375): This should be rewritten to allow concurrent calls. The
|
|
|
|
// difficulty is in ensuring that we correctly annotate events with the correct
|
|
|
|
// state deltas when sending to kafka streams
|
2020-07-07 13:51:55 +02:00
|
|
|
// TODO: Break up function - we should probably do transaction ID checks before calling this.
|
|
|
|
// nolint:gocyclo
|
2020-09-02 18:13:15 +02:00
|
|
|
func (r *Inputer) processRoomEvent(
|
2022-01-31 11:39:33 +01:00
|
|
|
ctx context.Context,
|
2020-09-03 16:22:16 +02:00
|
|
|
input *api.InputRoomEvent,
|
2022-02-23 16:41:32 +01:00
|
|
|
) error {
|
2022-01-27 15:29:14 +01:00
|
|
|
select {
|
2022-01-31 11:39:33 +01:00
|
|
|
case <-ctx.Done():
|
2022-01-27 15:29:14 +01:00
|
|
|
// Before we do anything, make sure the context hasn't expired for this pending task.
|
|
|
|
// If it has then we'll give up straight away — it's probably a synchronous input
|
|
|
|
// request and the caller has already given up, but the inbox task was still queued.
|
2022-02-23 16:41:32 +01:00
|
|
|
return context.DeadlineExceeded
|
2022-01-27 15:29:14 +01:00
|
|
|
default:
|
|
|
|
}
|
|
|
|
|
2022-06-07 15:23:26 +02:00
|
|
|
span, ctx := opentracing.StartSpanFromContext(ctx, "processRoomEvent")
|
|
|
|
span.SetTag("room_id", input.Event.RoomID())
|
|
|
|
span.SetTag("event_id", input.Event.EventID())
|
|
|
|
defer span.Finish()
|
|
|
|
|
2021-01-13 18:31:46 +01:00
|
|
|
// Measure how long it takes to process this event.
|
|
|
|
started := time.Now()
|
|
|
|
defer func() {
|
|
|
|
timetaken := time.Since(started)
|
|
|
|
processRoomEventDuration.With(prometheus.Labels{
|
|
|
|
"room_id": input.Event.RoomID(),
|
|
|
|
}).Observe(float64(timetaken.Milliseconds()))
|
|
|
|
}()
|
|
|
|
|
2017-02-07 18:20:05 +01:00
|
|
|
// Parse and validate the event JSON
|
2020-03-27 17:28:22 +01:00
|
|
|
headered := input.Event
|
|
|
|
event := headered.Unwrap()
|
2022-01-27 15:29:14 +01:00
|
|
|
logger := util.GetLogger(ctx).WithFields(logrus.Fields{
|
|
|
|
"event_id": event.EventID(),
|
|
|
|
"room_id": event.RoomID(),
|
2022-01-31 16:33:00 +01:00
|
|
|
"kind": input.Kind,
|
|
|
|
"origin": input.Origin,
|
2022-01-27 15:29:14 +01:00
|
|
|
"type": event.Type(),
|
|
|
|
})
|
2022-01-31 16:33:00 +01:00
|
|
|
if input.HasState {
|
|
|
|
logger = logger.WithFields(logrus.Fields{
|
|
|
|
"has_state": input.HasState,
|
|
|
|
"state_ids": len(input.StateEventIDs),
|
|
|
|
})
|
|
|
|
}
|
2017-02-07 18:20:05 +01:00
|
|
|
|
2020-10-20 12:42:54 +02:00
|
|
|
// if we have already got this event then do not process it again, if the input kind is an outlier.
|
|
|
|
// Outliers contain no extra information which may warrant a re-processing.
|
|
|
|
if input.Kind == api.KindOutlier {
|
2022-02-23 16:41:32 +01:00
|
|
|
evs, err2 := r.DB.EventsFromIDs(ctx, []string{event.EventID()})
|
2020-10-20 13:29:53 +02:00
|
|
|
if err2 == nil && len(evs) == 1 {
|
2020-10-20 12:42:54 +02:00
|
|
|
// check hash matches if we're on early room versions where the event ID was a random string
|
2020-10-20 13:29:53 +02:00
|
|
|
idFormat, err2 := headered.RoomVersion.EventIDFormat()
|
|
|
|
if err2 == nil {
|
2020-10-20 12:42:54 +02:00
|
|
|
switch idFormat {
|
|
|
|
case gomatrixserverlib.EventIDFormatV1:
|
|
|
|
if bytes.Equal(event.EventReference().EventSHA256, evs[0].EventReference().EventSHA256) {
|
2022-01-27 15:29:14 +01:00
|
|
|
logger.Debugf("Already processed event; ignoring")
|
2022-02-23 16:41:32 +01:00
|
|
|
return nil
|
2020-10-20 12:42:54 +02:00
|
|
|
}
|
|
|
|
default:
|
2022-01-27 15:29:14 +01:00
|
|
|
logger.Debugf("Already processed event; ignoring")
|
2022-02-23 16:41:32 +01:00
|
|
|
return nil
|
2020-10-20 12:42:54 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-02-11 18:40:14 +01:00
|
|
|
// Don't waste time processing the event if the room doesn't exist.
|
|
|
|
// A room entry locally will only be created in response to a create
|
|
|
|
// event.
|
2022-02-23 16:41:32 +01:00
|
|
|
roomInfo, rerr := r.DB.RoomInfo(ctx, event.RoomID())
|
|
|
|
if rerr != nil {
|
|
|
|
return fmt.Errorf("r.DB.RoomInfo: %w", rerr)
|
|
|
|
}
|
2022-02-11 18:40:14 +01:00
|
|
|
isCreateEvent := event.Type() == gomatrixserverlib.MRoomCreate && event.StateKeyEquals("")
|
2022-02-23 16:41:32 +01:00
|
|
|
if roomInfo == nil && !isCreateEvent {
|
|
|
|
return fmt.Errorf("room %s does not exist for event %s", event.RoomID(), event.EventID())
|
2022-02-11 18:40:14 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
var missingAuth, missingPrev bool
|
2022-01-27 15:29:14 +01:00
|
|
|
serverRes := &fedapi.QueryJoinedHostServerNamesInRoomResponse{}
|
2022-02-11 18:40:14 +01:00
|
|
|
if !isCreateEvent {
|
2022-02-23 16:41:32 +01:00
|
|
|
missingAuthIDs, missingPrevIDs, err := r.DB.MissingAuthPrevEvents(ctx, event)
|
2022-02-11 18:40:14 +01:00
|
|
|
if err != nil {
|
2022-02-23 16:41:32 +01:00
|
|
|
return fmt.Errorf("updater.MissingAuthPrevEvents: %w", err)
|
2022-01-27 15:29:14 +01:00
|
|
|
}
|
2022-02-11 18:40:14 +01:00
|
|
|
missingAuth = len(missingAuthIDs) > 0
|
|
|
|
missingPrev = !input.HasState && len(missingPrevIDs) > 0
|
2022-01-27 15:29:14 +01:00
|
|
|
}
|
2022-01-31 15:36:59 +01:00
|
|
|
|
|
|
|
if missingAuth || missingPrev {
|
2022-01-27 15:29:14 +01:00
|
|
|
serverReq := &fedapi.QueryJoinedHostServerNamesInRoomRequest{
|
|
|
|
RoomID: event.RoomID(),
|
|
|
|
ExcludeSelf: true,
|
|
|
|
}
|
2022-02-04 11:39:34 +01:00
|
|
|
if err := r.FSAPI.QueryJoinedHostServerNamesInRoom(ctx, serverReq, serverRes); err != nil {
|
2022-02-23 16:41:32 +01:00
|
|
|
return fmt.Errorf("r.FSAPI.QueryJoinedHostServerNamesInRoom: %w", err)
|
2022-01-27 15:29:14 +01:00
|
|
|
}
|
2022-01-31 15:36:59 +01:00
|
|
|
// Sort all of the servers into a map so that we can randomise
|
|
|
|
// their order. Then make sure that the input origin and the
|
|
|
|
// event origin are first on the list.
|
|
|
|
servers := map[gomatrixserverlib.ServerName]struct{}{}
|
|
|
|
for _, server := range serverRes.ServerNames {
|
|
|
|
servers[server] = struct{}{}
|
|
|
|
}
|
|
|
|
serverRes.ServerNames = serverRes.ServerNames[:0]
|
|
|
|
if input.Origin != "" {
|
|
|
|
serverRes.ServerNames = append(serverRes.ServerNames, input.Origin)
|
|
|
|
delete(servers, input.Origin)
|
|
|
|
}
|
|
|
|
if origin := event.Origin(); origin != input.Origin {
|
|
|
|
serverRes.ServerNames = append(serverRes.ServerNames, origin)
|
|
|
|
delete(servers, origin)
|
|
|
|
}
|
|
|
|
for server := range servers {
|
|
|
|
serverRes.ServerNames = append(serverRes.ServerNames, server)
|
|
|
|
delete(servers, server)
|
|
|
|
}
|
2022-01-27 15:29:14 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
// First of all, check that the auth events of the event are known.
|
|
|
|
// If they aren't then we will ask the federation API for them.
|
2020-09-16 14:00:52 +02:00
|
|
|
isRejected := false
|
2022-01-27 15:29:14 +01:00
|
|
|
authEvents := gomatrixserverlib.NewAuthEvents(nil)
|
|
|
|
knownEvents := map[string]*types.Event{}
|
2022-02-23 16:41:32 +01:00
|
|
|
if err := r.fetchAuthEvents(ctx, logger, headered, &authEvents, knownEvents, serverRes.ServerNames); err != nil {
|
|
|
|
return fmt.Errorf("r.fetchAuthEvents: %w", err)
|
2022-01-27 15:29:14 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
// Check if the event is allowed by its auth events. If it isn't then
|
|
|
|
// we consider the event to be "rejected" — it will still be persisted.
|
|
|
|
var rejectionErr error
|
|
|
|
if rejectionErr = gomatrixserverlib.Allowed(event, &authEvents); rejectionErr != nil {
|
2020-09-16 14:00:52 +02:00
|
|
|
isRejected = true
|
2022-01-31 13:01:53 +01:00
|
|
|
logger.WithError(rejectionErr).Warnf("Event %s not allowed by auth events", event.EventID())
|
2022-01-27 15:29:14 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
// Accumulate the auth event NIDs.
|
|
|
|
authEventIDs := event.AuthEventIDs()
|
|
|
|
authEventNIDs := make([]types.EventNID, 0, len(authEventIDs))
|
|
|
|
for _, authEventID := range authEventIDs {
|
|
|
|
if _, ok := knownEvents[authEventID]; !ok {
|
2022-02-08 18:06:13 +01:00
|
|
|
// Unknown auth events only really matter if the event actually failed
|
|
|
|
// auth. If it passed auth then we can assume that everything that was
|
|
|
|
// known was sufficient, even if extraneous auth events were specified
|
|
|
|
// but weren't found.
|
|
|
|
if isRejected {
|
|
|
|
if event.StateKey() != nil {
|
2022-02-23 16:41:32 +01:00
|
|
|
return fmt.Errorf(
|
2022-02-08 18:06:13 +01:00
|
|
|
"missing auth event %s for state event %s (type %q, state key %q)",
|
|
|
|
authEventID, event.EventID(), event.Type(), *event.StateKey(),
|
|
|
|
)
|
|
|
|
} else {
|
2022-02-23 16:41:32 +01:00
|
|
|
return fmt.Errorf(
|
2022-02-08 18:06:13 +01:00
|
|
|
"missing auth event %s for timeline event %s (type %q)",
|
|
|
|
authEventID, event.EventID(), event.Type(),
|
|
|
|
)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
authEventNIDs = append(authEventNIDs, knownEvents[authEventID].EventNID)
|
2022-01-27 15:29:14 +01:00
|
|
|
}
|
2018-05-26 13:03:35 +02:00
|
|
|
}
|
|
|
|
|
2020-09-21 15:55:46 +02:00
|
|
|
var softfail bool
|
2020-10-07 15:05:33 +02:00
|
|
|
if input.Kind == api.KindNew {
|
2020-09-21 15:55:46 +02:00
|
|
|
// Check that the event passes authentication checks based on the
|
|
|
|
// current room state.
|
2022-02-04 11:39:34 +01:00
|
|
|
var err error
|
2022-02-23 16:41:32 +01:00
|
|
|
softfail, err = helpers.CheckForSoftFail(ctx, r.DB, headered, input.StateEventIDs)
|
2020-09-21 15:55:46 +02:00
|
|
|
if err != nil {
|
2022-01-31 13:01:53 +01:00
|
|
|
logger.WithError(err).Warn("Error authing soft-failed event")
|
2022-01-27 15:29:14 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// At this point we are checking whether we know all of the prev events, and
|
|
|
|
// if we know the state before the prev events. This is necessary before we
|
|
|
|
// try to do `calculateAndSetState` on the event later, otherwise it will fail
|
|
|
|
// with missing event NIDs. If there's anything missing then we'll go and fetch
|
|
|
|
// the prev events and state from the federation. Note that we only do this if
|
|
|
|
// we weren't already told what the state before the event should be — if the
|
|
|
|
// HasState option was set and a state set was provided (as is the case in a
|
|
|
|
// typical federated room join) then we won't bother trying to fetch prev events
|
|
|
|
// because we may not be allowed to see them and we have no choice but to trust
|
|
|
|
// the state event IDs provided to us in the join instead.
|
|
|
|
if missingPrev && input.Kind == api.KindNew {
|
|
|
|
// Don't do this for KindOld events, otherwise old events that we fetch
|
|
|
|
// to satisfy missing prev events/state will end up recursively calling
|
|
|
|
// processRoomEvent.
|
|
|
|
if len(serverRes.ServerNames) > 0 {
|
|
|
|
missingState := missingStateReq{
|
|
|
|
origin: input.Origin,
|
|
|
|
inputer: r,
|
2022-02-23 16:41:32 +01:00
|
|
|
db: r.DB,
|
|
|
|
roomInfo: roomInfo,
|
2022-01-27 15:29:14 +01:00
|
|
|
federation: r.FSAPI,
|
|
|
|
keys: r.KeyRing,
|
|
|
|
roomsMu: internal.NewMutexByRoom(),
|
2022-01-31 15:36:59 +01:00
|
|
|
servers: serverRes.ServerNames,
|
2022-01-27 15:29:14 +01:00
|
|
|
hadEvents: map[string]bool{},
|
2022-02-11 18:40:14 +01:00
|
|
|
haveEvents: map[string]*gomatrixserverlib.Event{},
|
2022-01-27 15:29:14 +01:00
|
|
|
}
|
2022-02-10 11:05:14 +01:00
|
|
|
if stateSnapshot, err := missingState.processEventWithMissingState(ctx, event, headered.RoomVersion); err != nil {
|
|
|
|
// Something went wrong with retrieving the missing state, so we can't
|
|
|
|
// really do anything with the event other than reject it at this point.
|
2022-01-27 15:29:14 +01:00
|
|
|
isRejected = true
|
|
|
|
rejectionErr = fmt.Errorf("missingState.processEventWithMissingState: %w", err)
|
2022-02-10 11:05:14 +01:00
|
|
|
} else if stateSnapshot != nil {
|
|
|
|
// We retrieved some state and we ended up having to call /state_ids for
|
|
|
|
// the new event in question (probably because closing the gap by using
|
|
|
|
// /get_missing_events didn't do what we hoped) so we'll instead overwrite
|
|
|
|
// the state snapshot with the newly resolved state.
|
|
|
|
missingPrev = false
|
|
|
|
input.HasState = true
|
|
|
|
input.StateEventIDs = make([]string, 0, len(stateSnapshot.StateEvents))
|
|
|
|
for _, e := range stateSnapshot.StateEvents {
|
|
|
|
input.StateEventIDs = append(input.StateEventIDs, e.EventID())
|
|
|
|
}
|
2022-01-27 15:29:14 +01:00
|
|
|
} else {
|
2022-02-10 11:05:14 +01:00
|
|
|
// We retrieved some state and it would appear that rolling forward the
|
|
|
|
// state did everything we needed it to do, so we can just resolve the
|
|
|
|
// state for the event in the normal way.
|
2022-01-27 15:29:14 +01:00
|
|
|
missingPrev = false
|
|
|
|
}
|
|
|
|
} else {
|
2022-02-10 11:05:14 +01:00
|
|
|
// We're missing prev events or state for the event, but for some reason
|
|
|
|
// we don't know any servers to ask. In this case we can't do anything but
|
|
|
|
// reject the event and hope that it gets unrejected later.
|
2022-01-27 15:29:14 +01:00
|
|
|
isRejected = true
|
|
|
|
rejectionErr = fmt.Errorf("missing prev events and no other servers to ask")
|
2020-09-21 15:55:46 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-06-13 16:11:10 +02:00
|
|
|
// Get the state before the event so that we can work out if the event was
|
|
|
|
// allowed at the time, and also to get the history visibility. We won't
|
|
|
|
// bother doing this if the event was already rejected as it just ends up
|
|
|
|
// burning CPU time.
|
|
|
|
historyVisibility := gomatrixserverlib.HistoryVisibilityJoined // Default to restrictive.
|
|
|
|
if rejectionErr == nil && !isRejected && !softfail {
|
|
|
|
var err error
|
|
|
|
historyVisibility, rejectionErr, err = r.processStateBefore(ctx, input, missingPrev)
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("r.processStateBefore: %w", err)
|
|
|
|
}
|
|
|
|
if rejectionErr != nil {
|
|
|
|
isRejected = true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-05-18 18:49:24 +02:00
|
|
|
// Store the event.
|
2022-03-04 16:27:10 +01:00
|
|
|
_, _, stateAtEvent, redactionEvent, redactedEventID, err := r.DB.StoreEvent(ctx, event, authEventNIDs, isRejected || softfail)
|
2017-02-15 12:05:45 +01:00
|
|
|
if err != nil {
|
2022-02-23 16:41:32 +01:00
|
|
|
return fmt.Errorf("updater.StoreEvent: %w", err)
|
2017-02-09 17:48:14 +01:00
|
|
|
}
|
2020-09-16 14:00:52 +02:00
|
|
|
|
2020-07-07 13:51:55 +02:00
|
|
|
// if storing this event results in it being redacted then do so.
|
2020-09-16 14:00:52 +02:00
|
|
|
if !isRejected && redactedEventID == event.EventID() {
|
2022-07-11 15:31:31 +02:00
|
|
|
if err = eventutil.RedactEvent(redactionEvent, event); err != nil {
|
2022-02-23 16:41:32 +01:00
|
|
|
return fmt.Errorf("eventutil.RedactEvent: %w", rerr)
|
2020-07-07 13:51:55 +02:00
|
|
|
}
|
|
|
|
}
|
2017-02-07 18:20:05 +01:00
|
|
|
|
2020-05-18 18:49:24 +02:00
|
|
|
// For outliers we can stop after we've stored the event itself as it
|
|
|
|
// doesn't have any associated state to store and we don't need to
|
|
|
|
// notify anyone about it.
|
2017-02-07 18:20:05 +01:00
|
|
|
if input.Kind == api.KindOutlier {
|
2022-01-27 15:29:14 +01:00
|
|
|
logger.Debug("Stored outlier")
|
2022-01-28 14:11:56 +01:00
|
|
|
hooks.Run(hooks.KindNewEventPersisted, headered)
|
2022-02-23 16:41:32 +01:00
|
|
|
return nil
|
2017-02-07 18:20:05 +01:00
|
|
|
}
|
|
|
|
|
2022-02-23 16:41:32 +01:00
|
|
|
// Request the room info again — it's possible that the room has been
|
|
|
|
// created by now if it didn't exist already.
|
|
|
|
roomInfo, err = r.DB.RoomInfo(ctx, event.RoomID())
|
2020-09-02 11:02:48 +02:00
|
|
|
if err != nil {
|
2022-02-23 16:41:32 +01:00
|
|
|
return fmt.Errorf("updater.RoomInfo: %w", err)
|
2020-09-02 11:02:48 +02:00
|
|
|
}
|
|
|
|
if roomInfo == nil {
|
2022-02-23 16:41:32 +01:00
|
|
|
return fmt.Errorf("updater.RoomInfo missing for room %s", event.RoomID())
|
2020-09-02 11:02:48 +02:00
|
|
|
}
|
|
|
|
|
2022-02-10 11:05:14 +01:00
|
|
|
if input.HasState || (!missingPrev && stateAtEvent.BeforeStateSnapshotNID == 0) {
|
2017-02-15 12:05:45 +01:00
|
|
|
// We haven't calculated a state for this event yet.
|
|
|
|
// Lets calculate one.
|
2022-02-23 16:41:32 +01:00
|
|
|
err = r.calculateAndSetState(ctx, input, roomInfo, &stateAtEvent, event, isRejected)
|
2022-01-27 15:29:14 +01:00
|
|
|
if err != nil {
|
2022-02-23 16:41:32 +01:00
|
|
|
return fmt.Errorf("r.calculateAndSetState: %w", err)
|
2017-09-20 11:59:19 +02:00
|
|
|
}
|
2017-02-15 12:05:45 +01:00
|
|
|
}
|
|
|
|
|
2020-09-16 14:00:52 +02:00
|
|
|
// We stop here if the event is rejected: We've stored it but won't update forward extremities or notify anyone about it.
|
2020-09-21 15:55:46 +02:00
|
|
|
if isRejected || softfail {
|
2022-01-31 13:01:53 +01:00
|
|
|
logger.WithError(rejectionErr).WithFields(logrus.Fields{
|
|
|
|
"soft_fail": softfail,
|
|
|
|
"missing_prev": missingPrev,
|
|
|
|
}).Warn("Stored rejected event")
|
2022-02-07 20:10:01 +01:00
|
|
|
if rejectionErr != nil {
|
2022-02-23 16:41:32 +01:00
|
|
|
return types.RejectedError(rejectionErr.Error())
|
2022-02-07 20:10:01 +01:00
|
|
|
}
|
2022-02-23 16:41:32 +01:00
|
|
|
return nil
|
2020-09-16 14:00:52 +02:00
|
|
|
}
|
|
|
|
|
2020-10-19 15:59:13 +02:00
|
|
|
switch input.Kind {
|
|
|
|
case api.KindNew:
|
|
|
|
if err = r.updateLatestEvents(
|
|
|
|
ctx, // context
|
|
|
|
roomInfo, // room info for the room being updated
|
|
|
|
stateAtEvent, // state at event (below)
|
|
|
|
event, // event
|
|
|
|
input.SendAsServer, // send as server
|
|
|
|
input.TransactionID, // transaction ID
|
|
|
|
input.HasState, // rewrites state?
|
2022-06-13 16:11:10 +02:00
|
|
|
historyVisibility, // the history visibility before the event
|
2020-10-19 15:59:13 +02:00
|
|
|
); err != nil {
|
2022-02-23 16:41:32 +01:00
|
|
|
return fmt.Errorf("r.updateLatestEvents: %w", err)
|
2020-10-19 15:59:13 +02:00
|
|
|
}
|
|
|
|
case api.KindOld:
|
2022-07-01 11:54:07 +02:00
|
|
|
err = r.OutputProducer.ProduceRoomEvents(event.RoomID(), []api.OutputEvent{
|
2020-10-19 15:59:13 +02:00
|
|
|
{
|
|
|
|
Type: api.OutputTypeOldRoomEvent,
|
|
|
|
OldRoomEvent: &api.OutputOldRoomEvent{
|
2022-06-13 16:11:10 +02:00
|
|
|
Event: headered,
|
|
|
|
HistoryVisibility: historyVisibility,
|
2020-10-19 15:59:13 +02:00
|
|
|
},
|
|
|
|
},
|
|
|
|
})
|
|
|
|
if err != nil {
|
2022-02-23 16:41:32 +01:00
|
|
|
return fmt.Errorf("r.WriteOutputEvents (old): %w", err)
|
2020-10-19 15:59:13 +02:00
|
|
|
}
|
2020-05-18 18:49:24 +02:00
|
|
|
}
|
|
|
|
|
2020-07-07 13:51:55 +02:00
|
|
|
// processing this event resulted in an event (which may not be the one we're processing)
|
|
|
|
// being redacted. We are guaranteed to have both sides (the redaction/redacted event),
|
|
|
|
// so notify downstream components to redact this event - they should have it if they've
|
|
|
|
// been tracking our output log.
|
|
|
|
if redactedEventID != "" {
|
2022-07-01 11:54:07 +02:00
|
|
|
err = r.OutputProducer.ProduceRoomEvents(event.RoomID(), []api.OutputEvent{
|
2020-07-07 13:51:55 +02:00
|
|
|
{
|
|
|
|
Type: api.OutputTypeRedactedEvent,
|
|
|
|
RedactedEvent: &api.OutputRedactedEvent{
|
|
|
|
RedactedEventID: redactedEventID,
|
|
|
|
RedactedBecause: redactionEvent.Headered(headered.RoomVersion),
|
|
|
|
},
|
|
|
|
},
|
|
|
|
})
|
|
|
|
if err != nil {
|
2022-02-23 16:41:32 +01:00
|
|
|
return fmt.Errorf("r.WriteOutputEvents (redactions): %w", err)
|
2020-07-07 13:51:55 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-01-28 13:33:31 +01:00
|
|
|
// Everything was OK — the latest events updater didn't error and
|
|
|
|
// we've sent output events. Finally, generate a hook call.
|
|
|
|
hooks.Run(hooks.KindNewEventPersisted, headered)
|
2022-02-23 16:41:32 +01:00
|
|
|
return nil
|
2018-05-26 13:03:35 +02:00
|
|
|
}
|
|
|
|
|
2022-06-13 16:11:10 +02:00
|
|
|
// processStateBefore works out what the state is before the event and
|
|
|
|
// then checks the event auths against the state at the time. It also
|
|
|
|
// tries to determine what the history visibility was of the event at
|
|
|
|
// the time, so that it can be sent in the output event to downstream
|
|
|
|
// components.
|
|
|
|
// nolint:nakedret
|
|
|
|
func (r *Inputer) processStateBefore(
|
|
|
|
ctx context.Context,
|
|
|
|
input *api.InputRoomEvent,
|
|
|
|
missingPrev bool,
|
|
|
|
) (historyVisibility gomatrixserverlib.HistoryVisibility, rejectionErr error, err error) {
|
|
|
|
historyVisibility = gomatrixserverlib.HistoryVisibilityJoined // Default to restrictive.
|
|
|
|
event := input.Event.Unwrap()
|
|
|
|
isCreateEvent := event.Type() == gomatrixserverlib.MRoomCreate && event.StateKeyEquals("")
|
|
|
|
var stateBeforeEvent []*gomatrixserverlib.Event
|
|
|
|
switch {
|
|
|
|
case isCreateEvent:
|
|
|
|
// There's no state before a create event so there is nothing
|
|
|
|
// else to do.
|
|
|
|
return
|
|
|
|
case input.HasState:
|
|
|
|
// If we're overriding the state then we need to go and retrieve
|
|
|
|
// them from the database. It's a hard error if they are missing.
|
|
|
|
stateEvents, err := r.DB.EventsFromIDs(ctx, input.StateEventIDs)
|
|
|
|
if err != nil {
|
|
|
|
return "", nil, fmt.Errorf("r.DB.EventsFromIDs: %w", err)
|
|
|
|
}
|
|
|
|
stateBeforeEvent = make([]*gomatrixserverlib.Event, 0, len(stateEvents))
|
|
|
|
for _, entry := range stateEvents {
|
|
|
|
stateBeforeEvent = append(stateBeforeEvent, entry.Event)
|
|
|
|
}
|
|
|
|
case missingPrev:
|
|
|
|
// We don't know all of the prev events, so we can't work out
|
|
|
|
// the state before the event. Reject it in that case.
|
|
|
|
rejectionErr = fmt.Errorf("event %q has missing prev events", event.EventID())
|
|
|
|
return
|
|
|
|
case len(event.PrevEventIDs()) == 0:
|
|
|
|
// There should be prev events since it's not a create event.
|
|
|
|
// A non-create event that claims to have no prev events is
|
|
|
|
// invalid, so reject it.
|
|
|
|
rejectionErr = fmt.Errorf("event %q must have prev events", event.EventID())
|
|
|
|
return
|
|
|
|
default:
|
|
|
|
// For all non-create events, there must be prev events, so we'll
|
|
|
|
// ask the query API for the relevant tuples needed for auth. We
|
|
|
|
// will include the history visibility here even though we don't
|
|
|
|
// actually need it for auth, because we want to send it in the
|
|
|
|
// output events.
|
|
|
|
tuplesNeeded := gomatrixserverlib.StateNeededForAuth([]*gomatrixserverlib.Event{event}).Tuples()
|
|
|
|
tuplesNeeded = append(tuplesNeeded, gomatrixserverlib.StateKeyTuple{
|
|
|
|
EventType: gomatrixserverlib.MRoomHistoryVisibility,
|
|
|
|
StateKey: "",
|
|
|
|
})
|
|
|
|
stateBeforeReq := &api.QueryStateAfterEventsRequest{
|
|
|
|
RoomID: event.RoomID(),
|
|
|
|
PrevEventIDs: event.PrevEventIDs(),
|
|
|
|
StateToFetch: tuplesNeeded,
|
|
|
|
}
|
|
|
|
stateBeforeRes := &api.QueryStateAfterEventsResponse{}
|
|
|
|
if err := r.Queryer.QueryStateAfterEvents(ctx, stateBeforeReq, stateBeforeRes); err != nil {
|
|
|
|
return "", nil, fmt.Errorf("r.Queryer.QueryStateAfterEvents: %w", err)
|
|
|
|
}
|
|
|
|
switch {
|
|
|
|
case !stateBeforeRes.RoomExists:
|
|
|
|
rejectionErr = fmt.Errorf("room %q does not exist", event.RoomID())
|
|
|
|
return
|
|
|
|
case !stateBeforeRes.PrevEventsExist:
|
|
|
|
rejectionErr = fmt.Errorf("prev events of %q are not known", event.EventID())
|
|
|
|
return
|
|
|
|
default:
|
|
|
|
stateBeforeEvent = gomatrixserverlib.UnwrapEventHeaders(stateBeforeRes.StateEvents)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
// At this point, stateBeforeEvent should be populated either by
|
|
|
|
// the supplied state in the input request, or from the prev events.
|
|
|
|
// Check whether the event is allowed or not.
|
|
|
|
stateBeforeAuth := gomatrixserverlib.NewAuthEvents(stateBeforeEvent)
|
|
|
|
if rejectionErr = gomatrixserverlib.Allowed(event, &stateBeforeAuth); rejectionErr != nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
// Work out what the history visibility was at the time of the
|
|
|
|
// event.
|
|
|
|
for _, event := range stateBeforeEvent {
|
|
|
|
if event.Type() != gomatrixserverlib.MRoomHistoryVisibility || !event.StateKeyEquals("") {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
if hisVis, err := event.HistoryVisibility(); err == nil {
|
|
|
|
historyVisibility = hisVis
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2022-01-27 15:29:14 +01:00
|
|
|
// fetchAuthEvents will check to see if any of the
|
|
|
|
// auth events specified by the given event are unknown. If they are
|
|
|
|
// then we will go off and request them from the federation and then
|
|
|
|
// store them in the database. By the time this function ends, either
|
|
|
|
// we've failed to retrieve the auth chain altogether (in which case
|
|
|
|
// an error is returned) or we've successfully retrieved them all and
|
|
|
|
// they are now in the database.
|
|
|
|
func (r *Inputer) fetchAuthEvents(
|
|
|
|
ctx context.Context,
|
|
|
|
logger *logrus.Entry,
|
|
|
|
event *gomatrixserverlib.HeaderedEvent,
|
|
|
|
auth *gomatrixserverlib.AuthEvents,
|
|
|
|
known map[string]*types.Event,
|
|
|
|
servers []gomatrixserverlib.ServerName,
|
|
|
|
) error {
|
2022-06-07 15:23:26 +02:00
|
|
|
span, ctx := opentracing.StartSpanFromContext(ctx, "fetchAuthEvents")
|
|
|
|
defer span.Finish()
|
|
|
|
|
2022-01-27 15:29:14 +01:00
|
|
|
unknown := map[string]struct{}{}
|
|
|
|
authEventIDs := event.AuthEventIDs()
|
|
|
|
if len(authEventIDs) == 0 {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
for _, authEventID := range authEventIDs {
|
2022-02-23 16:41:32 +01:00
|
|
|
authEvents, err := r.DB.EventsFromIDs(ctx, []string{authEventID})
|
2022-01-27 15:29:14 +01:00
|
|
|
if err != nil || len(authEvents) == 0 || authEvents[0].Event == nil {
|
|
|
|
unknown[authEventID] = struct{}{}
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
ev := authEvents[0]
|
|
|
|
known[authEventID] = &ev // don't take the pointer of the iterated event
|
|
|
|
if err = auth.AddEvent(ev.Event); err != nil {
|
|
|
|
return fmt.Errorf("auth.AddEvent: %w", err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// If there are no missing auth events then there is nothing more
|
|
|
|
// to do — we've loaded everything that we need.
|
|
|
|
if len(unknown) == 0 {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
var err error
|
|
|
|
var res gomatrixserverlib.RespEventAuth
|
|
|
|
var found bool
|
|
|
|
for _, serverName := range servers {
|
|
|
|
// Request the entire auth chain for the event in question. This should
|
|
|
|
// contain all of the auth events — including ones that we already know —
|
|
|
|
// so we'll need to filter through those in the next section.
|
|
|
|
res, err = r.FSAPI.GetEventAuth(ctx, serverName, event.RoomVersion, event.RoomID(), event.EventID())
|
|
|
|
if err != nil {
|
|
|
|
logger.WithError(err).Warnf("Failed to get event auth from federation for %q: %s", event.EventID(), err)
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
found = true
|
|
|
|
break
|
|
|
|
}
|
|
|
|
if !found {
|
|
|
|
return fmt.Errorf("no servers provided event auth for event ID %q, tried servers %v", event.EventID(), servers)
|
|
|
|
}
|
|
|
|
|
2022-02-08 18:06:13 +01:00
|
|
|
// Reuse these to reduce allocations.
|
|
|
|
authEventNIDs := make([]types.EventNID, 0, 5)
|
|
|
|
isRejected := false
|
|
|
|
nextAuthEvent:
|
2022-01-27 15:29:14 +01:00
|
|
|
for _, authEvent := range gomatrixserverlib.ReverseTopologicalOrdering(
|
2022-02-09 21:31:24 +01:00
|
|
|
res.AuthEvents.UntrustedEvents(event.RoomVersion),
|
2022-01-27 15:29:14 +01:00
|
|
|
gomatrixserverlib.TopologicalOrderByAuthEvents,
|
|
|
|
) {
|
|
|
|
// If we already know about this event from the database then we don't
|
|
|
|
// need to store it again or do anything further with it, so just skip
|
|
|
|
// over it rather than wasting cycles.
|
|
|
|
if ev, ok := known[authEvent.EventID()]; ok && ev != nil {
|
2022-02-08 18:06:13 +01:00
|
|
|
continue nextAuthEvent
|
2022-01-27 15:29:14 +01:00
|
|
|
}
|
|
|
|
|
2022-01-31 15:36:59 +01:00
|
|
|
// Check the signatures of the event. If this fails then we'll simply
|
|
|
|
// skip it, because gomatrixserverlib.Allowed() will notice a problem
|
|
|
|
// if a critical event is missing anyway.
|
2022-01-27 15:29:14 +01:00
|
|
|
if err := authEvent.VerifyEventSignatures(ctx, r.FSAPI.KeyRing()); err != nil {
|
2022-02-08 18:06:13 +01:00
|
|
|
continue nextAuthEvent
|
2022-01-27 15:29:14 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
// In order to store the new auth event, we need to know its auth chain
|
|
|
|
// as NIDs for the `auth_event_nids` column. Let's see if we can find those.
|
2022-02-08 18:06:13 +01:00
|
|
|
authEventNIDs = authEventNIDs[:0]
|
2022-01-27 15:29:14 +01:00
|
|
|
for _, eventID := range authEvent.AuthEventIDs() {
|
|
|
|
knownEvent, ok := known[eventID]
|
|
|
|
if !ok {
|
2022-02-08 18:06:13 +01:00
|
|
|
continue nextAuthEvent
|
2022-01-27 15:29:14 +01:00
|
|
|
}
|
|
|
|
authEventNIDs = append(authEventNIDs, knownEvent.EventNID)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Check if the auth event should be rejected.
|
2022-02-08 18:06:13 +01:00
|
|
|
err := gomatrixserverlib.Allowed(authEvent, auth)
|
|
|
|
if isRejected = err != nil; isRejected {
|
2022-01-27 15:29:14 +01:00
|
|
|
logger.WithError(err).Warnf("Auth event %s rejected", authEvent.EventID())
|
|
|
|
}
|
|
|
|
|
|
|
|
// Finally, store the event in the database.
|
2022-02-23 16:41:32 +01:00
|
|
|
eventNID, _, _, _, _, err := r.DB.StoreEvent(ctx, authEvent, authEventNIDs, isRejected)
|
2022-01-27 15:29:14 +01:00
|
|
|
if err != nil {
|
2022-02-04 11:39:34 +01:00
|
|
|
return fmt.Errorf("updater.StoreEvent: %w", err)
|
2022-01-27 15:29:14 +01:00
|
|
|
}
|
|
|
|
|
2022-02-08 18:06:13 +01:00
|
|
|
// Let's take a note of the fact that we now know about this event for
|
|
|
|
// authenticating future events.
|
|
|
|
if !isRejected {
|
|
|
|
if err := auth.AddEvent(authEvent); err != nil {
|
|
|
|
return fmt.Errorf("auth.AddEvent: %w", err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-01-27 15:29:14 +01:00
|
|
|
// Now we know about this event, it was stored and the signatures were OK.
|
|
|
|
known[authEvent.EventID()] = &types.Event{
|
|
|
|
EventNID: eventNID,
|
|
|
|
Event: authEvent,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2020-09-02 18:13:15 +02:00
|
|
|
func (r *Inputer) calculateAndSetState(
|
2018-05-26 13:03:35 +02:00
|
|
|
ctx context.Context,
|
2020-09-03 16:22:16 +02:00
|
|
|
input *api.InputRoomEvent,
|
2022-01-27 15:29:14 +01:00
|
|
|
roomInfo *types.RoomInfo,
|
2018-05-26 13:03:35 +02:00
|
|
|
stateAtEvent *types.StateAtEvent,
|
2020-11-16 16:44:53 +01:00
|
|
|
event *gomatrixserverlib.Event,
|
2020-09-16 14:00:52 +02:00
|
|
|
isRejected bool,
|
2018-05-26 13:03:35 +02:00
|
|
|
) error {
|
2022-06-07 15:23:26 +02:00
|
|
|
span, ctx := opentracing.StartSpanFromContext(ctx, "calculateAndSetState")
|
|
|
|
defer span.Finish()
|
|
|
|
|
2022-02-23 16:41:32 +01:00
|
|
|
var succeeded bool
|
|
|
|
updater, err := r.DB.GetRoomUpdater(ctx, roomInfo)
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("r.DB.GetRoomUpdater: %w", err)
|
|
|
|
}
|
|
|
|
defer sqlutil.EndTransactionWithCheck(updater, &succeeded, &err)
|
2022-02-04 11:39:34 +01:00
|
|
|
roomState := state.NewStateResolution(updater, roomInfo)
|
2020-02-05 17:25:58 +01:00
|
|
|
|
2022-01-31 15:36:59 +01:00
|
|
|
if input.HasState {
|
2018-05-26 13:03:35 +02:00
|
|
|
// We've been told what the state at the event is so we don't need to calculate it.
|
|
|
|
// Check that those state events are in the database and store the state.
|
|
|
|
var entries []types.StateEntry
|
2022-02-23 16:41:32 +01:00
|
|
|
if entries, err = r.DB.StateEntriesForEventIDs(ctx, input.StateEventIDs); err != nil {
|
2022-02-04 11:39:34 +01:00
|
|
|
return fmt.Errorf("updater.StateEntriesForEventIDs: %w", err)
|
2018-05-26 13:03:35 +02:00
|
|
|
}
|
2020-09-15 12:17:46 +02:00
|
|
|
entries = types.DeduplicateStateEntries(entries)
|
2018-05-26 13:03:35 +02:00
|
|
|
|
2022-02-04 11:39:34 +01:00
|
|
|
if stateAtEvent.BeforeStateSnapshotNID, err = updater.AddState(ctx, roomInfo.RoomNID, nil, entries); err != nil {
|
|
|
|
return fmt.Errorf("updater.AddState: %w", err)
|
2018-05-26 13:03:35 +02:00
|
|
|
}
|
|
|
|
} else {
|
|
|
|
// We haven't been told what the state at the event is so we need to calculate it from the prev_events
|
2020-09-16 14:00:52 +02:00
|
|
|
if stateAtEvent.BeforeStateSnapshotNID, err = roomState.CalculateAndStoreStateBeforeEvent(ctx, event, isRejected); err != nil {
|
2020-09-15 12:17:46 +02:00
|
|
|
return fmt.Errorf("roomState.CalculateAndStoreStateBeforeEvent: %w", err)
|
2018-05-26 13:03:35 +02:00
|
|
|
}
|
|
|
|
}
|
2020-09-15 12:17:46 +02:00
|
|
|
|
2022-02-04 11:39:34 +01:00
|
|
|
err = updater.SetState(ctx, stateAtEvent.EventNID, stateAtEvent.BeforeStateSnapshotNID)
|
2020-09-15 12:17:46 +02:00
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("r.DB.SetState: %w", err)
|
|
|
|
}
|
2022-02-23 16:41:32 +01:00
|
|
|
succeeded = true
|
2020-09-15 12:17:46 +02:00
|
|
|
return nil
|
2017-08-21 17:37:11 +02:00
|
|
|
}
|