2017-04-20 22:40:52 +00:00
|
|
|
// Copyright 2017 Vector Creations Ltd
|
2020-02-05 18:06:39 +00:00
|
|
|
// Copyright 2018 New Vector Ltd
|
|
|
|
// Copyright 2019-2020 The Matrix.org Foundation C.I.C.
|
2017-04-20 22:40:52 +00: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 16:13:15 +00:00
|
|
|
package input
|
2017-02-07 17:20:05 +00:00
|
|
|
|
|
|
|
import (
|
2017-09-13 15:30:19 +00:00
|
|
|
"context"
|
2022-08-18 09:37:47 +00:00
|
|
|
"database/sql"
|
2022-12-22 12:05:59 +00:00
|
|
|
"encoding/json"
|
2022-10-14 07:14:54 +00:00
|
|
|
"errors"
|
2020-07-21 14:48:21 +00:00
|
|
|
"fmt"
|
2021-01-13 17:31:46 +00:00
|
|
|
"time"
|
2017-08-21 15:37:11 +00:00
|
|
|
|
2022-11-14 12:07:13 +00:00
|
|
|
"github.com/tidwall/gjson"
|
|
|
|
|
2023-03-01 16:06:47 +00:00
|
|
|
"github.com/matrix-org/dendrite/roomserver/internal/helpers"
|
|
|
|
|
2022-10-14 07:14:54 +00:00
|
|
|
"github.com/matrix-org/gomatrixserverlib"
|
|
|
|
"github.com/matrix-org/util"
|
|
|
|
"github.com/opentracing/opentracing-go"
|
|
|
|
"github.com/prometheus/client_golang/prometheus"
|
|
|
|
"github.com/sirupsen/logrus"
|
|
|
|
|
2022-12-22 12:05:59 +00:00
|
|
|
userAPI "github.com/matrix-org/dendrite/userapi/api"
|
|
|
|
|
2022-01-27 14:29:14 +00:00
|
|
|
fedapi "github.com/matrix-org/dendrite/federationapi/api"
|
|
|
|
"github.com/matrix-org/dendrite/internal"
|
2020-07-07 11:51:55 +00:00
|
|
|
"github.com/matrix-org/dendrite/internal/eventutil"
|
2022-01-28 12:33:31 +00:00
|
|
|
"github.com/matrix-org/dendrite/internal/hooks"
|
2022-02-23 15:41:32 +00:00
|
|
|
"github.com/matrix-org/dendrite/internal/sqlutil"
|
2017-02-07 17:20:05 +00:00
|
|
|
"github.com/matrix-org/dendrite/roomserver/api"
|
2017-03-08 15:10:26 +00:00
|
|
|
"github.com/matrix-org/dendrite/roomserver/state"
|
2017-02-09 16:48:14 +00:00
|
|
|
"github.com/matrix-org/dendrite/roomserver/types"
|
2017-02-07 17:20:05 +00:00
|
|
|
)
|
|
|
|
|
2022-01-27 14:29:14 +00:00
|
|
|
// TODO: Does this value make sense?
|
2022-01-31 10:39:33 +00:00
|
|
|
const MaximumMissingProcessingTime = time.Minute * 2
|
2022-01-27 14:29:14 +00:00
|
|
|
|
2021-01-13 17:31:46 +00: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 15:22:06 +00: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 11:51:55 +00:00
|
|
|
// TODO: Break up function - we should probably do transaction ID checks before calling this.
|
|
|
|
// nolint:gocyclo
|
2020-09-02 16:13:15 +00:00
|
|
|
func (r *Inputer) processRoomEvent(
|
2022-01-31 10:39:33 +00:00
|
|
|
ctx context.Context,
|
2022-11-15 15:05:23 +00:00
|
|
|
virtualHost gomatrixserverlib.ServerName,
|
2020-09-03 14:22:16 +00:00
|
|
|
input *api.InputRoomEvent,
|
2022-02-23 15:41:32 +00:00
|
|
|
) error {
|
2022-01-27 14:29:14 +00:00
|
|
|
select {
|
2022-01-31 10:39:33 +00:00
|
|
|
case <-ctx.Done():
|
2022-01-27 14:29:14 +00: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 15:41:32 +00:00
|
|
|
return context.DeadlineExceeded
|
2022-01-27 14:29:14 +00:00
|
|
|
default:
|
|
|
|
}
|
|
|
|
|
2022-06-07 13:23:26 +00: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 17:31:46 +00: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 17:20:05 +00:00
|
|
|
// Parse and validate the event JSON
|
2020-03-27 16:28:22 +00:00
|
|
|
headered := input.Event
|
|
|
|
event := headered.Unwrap()
|
2022-01-27 14:29:14 +00:00
|
|
|
logger := util.GetLogger(ctx).WithFields(logrus.Fields{
|
|
|
|
"event_id": event.EventID(),
|
|
|
|
"room_id": event.RoomID(),
|
2022-01-31 15:33:00 +00:00
|
|
|
"kind": input.Kind,
|
|
|
|
"origin": input.Origin,
|
2022-01-27 14:29:14 +00:00
|
|
|
"type": event.Type(),
|
|
|
|
})
|
2022-01-31 15:33:00 +00:00
|
|
|
if input.HasState {
|
|
|
|
logger = logger.WithFields(logrus.Fields{
|
|
|
|
"has_state": input.HasState,
|
|
|
|
"state_ids": len(input.StateEventIDs),
|
|
|
|
})
|
|
|
|
}
|
2017-02-07 17:20:05 +00:00
|
|
|
|
2022-02-11 17:40:14 +00: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 15:41:32 +00:00
|
|
|
roomInfo, rerr := r.DB.RoomInfo(ctx, event.RoomID())
|
|
|
|
if rerr != nil {
|
|
|
|
return fmt.Errorf("r.DB.RoomInfo: %w", rerr)
|
|
|
|
}
|
2022-02-11 17:40:14 +00:00
|
|
|
isCreateEvent := event.Type() == gomatrixserverlib.MRoomCreate && event.StateKeyEquals("")
|
2022-02-23 15:41:32 +00:00
|
|
|
if roomInfo == nil && !isCreateEvent {
|
|
|
|
return fmt.Errorf("room %s does not exist for event %s", event.RoomID(), event.EventID())
|
2022-02-11 17:40:14 +00:00
|
|
|
}
|
2022-09-26 16:35:35 +00:00
|
|
|
_, senderDomain, err := gomatrixserverlib.SplitID('@', event.Sender())
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("event has invalid sender %q", input.Event.Sender())
|
|
|
|
}
|
2022-02-11 17:40:14 +00:00
|
|
|
|
2022-08-18 09:37:47 +00:00
|
|
|
// If we already know about this outlier and it hasn't been rejected
|
|
|
|
// then we won't attempt to reprocess it. If it was rejected or has now
|
|
|
|
// arrived as a different kind of event, then we can attempt to reprocess,
|
|
|
|
// in case we have learned something new or need to weave the event into
|
|
|
|
// the DAG now.
|
|
|
|
if input.Kind == api.KindOutlier && roomInfo != nil {
|
|
|
|
wasRejected, werr := r.DB.IsEventRejected(ctx, roomInfo.RoomNID, event.EventID())
|
|
|
|
switch {
|
|
|
|
case werr == sql.ErrNoRows:
|
|
|
|
// We haven't seen this event before so continue.
|
|
|
|
case werr != nil:
|
|
|
|
// Something has gone wrong trying to find out if we rejected
|
|
|
|
// this event already.
|
|
|
|
logger.WithError(werr).Errorf("Failed to check if event %q is already seen", event.EventID())
|
|
|
|
return werr
|
|
|
|
case !wasRejected:
|
|
|
|
// We've seen this event before and it wasn't rejected so we
|
|
|
|
// should ignore it.
|
|
|
|
logger.Debugf("Already processed event %q, ignoring", event.EventID())
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-02-11 17:40:14 +00:00
|
|
|
var missingAuth, missingPrev bool
|
2022-01-27 14:29:14 +00:00
|
|
|
serverRes := &fedapi.QueryJoinedHostServerNamesInRoomResponse{}
|
2022-02-11 17:40:14 +00:00
|
|
|
if !isCreateEvent {
|
2022-09-26 16:35:35 +00:00
|
|
|
var missingAuthIDs, missingPrevIDs []string
|
|
|
|
missingAuthIDs, missingPrevIDs, err = r.DB.MissingAuthPrevEvents(ctx, event)
|
2022-02-11 17:40:14 +00:00
|
|
|
if err != nil {
|
2022-02-23 15:41:32 +00:00
|
|
|
return fmt.Errorf("updater.MissingAuthPrevEvents: %w", err)
|
2022-01-27 14:29:14 +00:00
|
|
|
}
|
2022-02-11 17:40:14 +00:00
|
|
|
missingAuth = len(missingAuthIDs) > 0
|
|
|
|
missingPrev = !input.HasState && len(missingPrevIDs) > 0
|
2022-01-27 14:29:14 +00:00
|
|
|
}
|
2022-01-31 14:36:59 +00:00
|
|
|
|
2023-01-20 14:18:06 +00:00
|
|
|
// If we have missing events (auth or prev), we build a list of servers to ask
|
2022-01-31 14:36:59 +00:00
|
|
|
if missingAuth || missingPrev {
|
2022-01-27 14:29:14 +00:00
|
|
|
serverReq := &fedapi.QueryJoinedHostServerNamesInRoomRequest{
|
2022-11-15 17:21:16 +00:00
|
|
|
RoomID: event.RoomID(),
|
|
|
|
ExcludeSelf: true,
|
|
|
|
ExcludeBlacklisted: true,
|
2022-01-27 14:29:14 +00:00
|
|
|
}
|
2022-09-26 16:35:35 +00:00
|
|
|
if err = r.FSAPI.QueryJoinedHostServerNamesInRoom(ctx, serverReq, serverRes); err != nil {
|
2022-02-23 15:41:32 +00:00
|
|
|
return fmt.Errorf("r.FSAPI.QueryJoinedHostServerNamesInRoom: %w", err)
|
2022-01-27 14:29:14 +00:00
|
|
|
}
|
2022-01-31 14:36:59 +00: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{}{}
|
|
|
|
}
|
2022-10-06 09:51:06 +00:00
|
|
|
// Don't try to talk to ourselves.
|
|
|
|
delete(servers, r.Cfg.Matrix.ServerName)
|
|
|
|
// Now build up the list of servers.
|
2022-01-31 14:36:59 +00:00
|
|
|
serverRes.ServerNames = serverRes.ServerNames[:0]
|
2022-10-06 09:51:06 +00:00
|
|
|
if input.Origin != "" && input.Origin != r.Cfg.Matrix.ServerName {
|
2022-01-31 14:36:59 +00:00
|
|
|
serverRes.ServerNames = append(serverRes.ServerNames, input.Origin)
|
|
|
|
delete(servers, input.Origin)
|
|
|
|
}
|
2022-10-06 09:51:06 +00:00
|
|
|
if senderDomain != input.Origin && senderDomain != r.Cfg.Matrix.ServerName {
|
2022-09-26 16:35:35 +00:00
|
|
|
serverRes.ServerNames = append(serverRes.ServerNames, senderDomain)
|
|
|
|
delete(servers, senderDomain)
|
2022-01-31 14:36:59 +00:00
|
|
|
}
|
|
|
|
for server := range servers {
|
|
|
|
serverRes.ServerNames = append(serverRes.ServerNames, server)
|
|
|
|
delete(servers, server)
|
|
|
|
}
|
2022-01-27 14:29:14 +00:00
|
|
|
}
|
|
|
|
|
2020-09-16 12:00:52 +00:00
|
|
|
isRejected := false
|
2022-01-27 14:29:14 +00:00
|
|
|
var rejectionErr error
|
|
|
|
|
|
|
|
// 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{
|
2022-11-15 15:05:23 +00:00
|
|
|
origin: input.Origin,
|
|
|
|
virtualHost: virtualHost,
|
|
|
|
inputer: r,
|
|
|
|
db: r.DB,
|
|
|
|
roomInfo: roomInfo,
|
|
|
|
federation: r.FSAPI,
|
|
|
|
keys: r.KeyRing,
|
|
|
|
roomsMu: internal.NewMutexByRoom(),
|
|
|
|
servers: serverRes.ServerNames,
|
|
|
|
hadEvents: map[string]bool{},
|
|
|
|
haveEvents: map[string]*gomatrixserverlib.Event{},
|
2022-01-27 14:29:14 +00:00
|
|
|
}
|
2022-09-26 16:35:35 +00:00
|
|
|
var stateSnapshot *parsedRespState
|
|
|
|
if stateSnapshot, err = missingState.processEventWithMissingState(ctx, event, headered.RoomVersion); err != nil {
|
2022-02-10 10:05:14 +00:00
|
|
|
// 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 14:29:14 +00:00
|
|
|
isRejected = true
|
|
|
|
rejectionErr = fmt.Errorf("missingState.processEventWithMissingState: %w", err)
|
2022-02-10 10:05:14 +00: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 14:29:14 +00:00
|
|
|
} else {
|
2022-02-10 10:05:14 +00: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 14:29:14 +00:00
|
|
|
missingPrev = false
|
|
|
|
}
|
|
|
|
} else {
|
2022-02-10 10:05:14 +00: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 14:29:14 +00:00
|
|
|
isRejected = true
|
|
|
|
rejectionErr = fmt.Errorf("missing prev events and no other servers to ask")
|
2020-09-21 13:55:46 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-01-20 14:18:06 +00:00
|
|
|
// Check that the auth events of the event are known.
|
|
|
|
// If they aren't then we will ask the federation API for them.
|
|
|
|
authEvents := gomatrixserverlib.NewAuthEvents(nil)
|
|
|
|
knownEvents := map[string]*types.Event{}
|
|
|
|
if err = r.fetchAuthEvents(ctx, logger, roomInfo, virtualHost, headered, &authEvents, knownEvents, serverRes.ServerNames); err != nil {
|
|
|
|
return fmt.Errorf("r.fetchAuthEvents: %w", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
// 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.
|
2023-03-01 16:06:47 +00:00
|
|
|
redactAllowed := true
|
2023-01-20 14:18:06 +00:00
|
|
|
if err = gomatrixserverlib.Allowed(event, &authEvents); err != nil {
|
|
|
|
isRejected = true
|
2023-03-01 16:06:47 +00:00
|
|
|
redactAllowed = false
|
2023-01-20 14:18:06 +00:00
|
|
|
rejectionErr = err
|
|
|
|
logger.WithError(rejectionErr).Warnf("Event %s not allowed by auth events", event.EventID())
|
|
|
|
}
|
|
|
|
|
|
|
|
// Accumulate the auth event NIDs.
|
|
|
|
authEventIDs := event.AuthEventIDs()
|
|
|
|
authEventNIDs := make([]types.EventNID, 0, len(authEventIDs))
|
|
|
|
for _, authEventID := range authEventIDs {
|
|
|
|
if _, ok := knownEvents[authEventID]; !ok {
|
|
|
|
// 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 {
|
|
|
|
return fmt.Errorf(
|
|
|
|
"missing auth event %s for state event %s (type %q, state key %q)",
|
|
|
|
authEventID, event.EventID(), event.Type(), *event.StateKey(),
|
|
|
|
)
|
|
|
|
} else {
|
|
|
|
return fmt.Errorf(
|
|
|
|
"missing auth event %s for timeline event %s (type %q)",
|
|
|
|
authEventID, event.EventID(), event.Type(),
|
|
|
|
)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
authEventNIDs = append(authEventNIDs, knownEvents[authEventID].EventNID)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
var softfail bool
|
2023-02-24 08:40:20 +00:00
|
|
|
if input.Kind == api.KindNew && !isCreateEvent {
|
2023-01-20 14:18:06 +00:00
|
|
|
// Check that the event passes authentication checks based on the
|
|
|
|
// current room state.
|
2023-02-24 08:40:20 +00:00
|
|
|
softfail, err = helpers.CheckForSoftFail(ctx, r.DB, roomInfo, headered, input.StateEventIDs)
|
2023-01-20 14:18:06 +00:00
|
|
|
if err != nil {
|
|
|
|
logger.WithError(err).Warn("Error authing soft-failed event")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-06-13 14:11:10 +00: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.
|
2022-08-11 16:23:35 +00:00
|
|
|
historyVisibility := gomatrixserverlib.HistoryVisibilityShared // Default to shared.
|
2023-02-24 08:40:20 +00:00
|
|
|
if input.Kind != api.KindOutlier && rejectionErr == nil && !isRejected && !isCreateEvent {
|
2023-03-01 16:06:47 +00:00
|
|
|
historyVisibility, rejectionErr, err = r.processStateBefore(ctx, roomInfo, input, missingPrev)
|
2022-06-13 14:11:10 +00:00
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("r.processStateBefore: %w", err)
|
|
|
|
}
|
|
|
|
if rejectionErr != nil {
|
|
|
|
isRejected = true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-03-01 16:06:47 +00:00
|
|
|
if roomInfo == nil {
|
|
|
|
roomInfo, err = r.DB.GetOrCreateRoomInfo(ctx, event)
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("r.DB.GetOrCreateRoomInfo: %w", err)
|
|
|
|
}
|
2023-02-24 08:40:20 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
eventTypeNID, err := r.DB.GetOrCreateEventTypeNID(ctx, event.Type())
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("r.DB.GetOrCreateEventTypeNID: %w", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
eventStateKeyNID, err := r.DB.GetOrCreateEventStateKeyNID(ctx, event.StateKey())
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("r.DB.GetOrCreateEventStateKeyNID: %w", err)
|
|
|
|
}
|
|
|
|
|
2020-05-18 16:49:24 +00:00
|
|
|
// Store the event.
|
2023-03-01 16:06:47 +00:00
|
|
|
eventNID, stateAtEvent, err := r.DB.StoreEvent(ctx, event, roomInfo, eventTypeNID, eventStateKeyNID, authEventNIDs, isRejected)
|
2017-02-15 11:05:45 +00:00
|
|
|
if err != nil {
|
2022-02-23 15:41:32 +00:00
|
|
|
return fmt.Errorf("updater.StoreEvent: %w", err)
|
2017-02-09 16:48:14 +00:00
|
|
|
}
|
2020-09-16 12:00:52 +00:00
|
|
|
|
2020-07-07 11:51:55 +00:00
|
|
|
// if storing this event results in it being redacted then do so.
|
2023-03-01 16:06:47 +00:00
|
|
|
var (
|
|
|
|
redactedEventID string
|
|
|
|
redactionEvent *gomatrixserverlib.Event
|
|
|
|
redactedEvent *gomatrixserverlib.Event
|
|
|
|
)
|
|
|
|
if !isRejected && !isCreateEvent {
|
|
|
|
redactionEvent, redactedEvent, err = r.DB.MaybeRedactEvent(ctx, roomInfo, eventNID, event, redactAllowed)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
if redactedEvent != nil {
|
|
|
|
redactedEventID = redactedEvent.EventID()
|
2020-07-07 11:51:55 +00:00
|
|
|
}
|
|
|
|
}
|
2017-02-07 17:20:05 +00:00
|
|
|
|
2020-05-18 16:49:24 +00: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 17:20:05 +00:00
|
|
|
if input.Kind == api.KindOutlier {
|
2022-10-14 07:14:54 +00:00
|
|
|
logger.WithField("rejected", isRejected).Debug("Stored outlier")
|
2022-01-28 13:11:56 +00:00
|
|
|
hooks.Run(hooks.KindNewEventPersisted, headered)
|
2022-02-23 15:41:32 +00:00
|
|
|
return nil
|
2017-02-07 17:20:05 +00:00
|
|
|
}
|
|
|
|
|
2022-02-23 15:41:32 +00: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 09:02:48 +00:00
|
|
|
if err != nil {
|
2022-02-23 15:41:32 +00:00
|
|
|
return fmt.Errorf("updater.RoomInfo: %w", err)
|
2020-09-02 09:02:48 +00:00
|
|
|
}
|
|
|
|
if roomInfo == nil {
|
2022-02-23 15:41:32 +00:00
|
|
|
return fmt.Errorf("updater.RoomInfo missing for room %s", event.RoomID())
|
2020-09-02 09:02:48 +00:00
|
|
|
}
|
|
|
|
|
2022-02-10 10:05:14 +00:00
|
|
|
if input.HasState || (!missingPrev && stateAtEvent.BeforeStateSnapshotNID == 0) {
|
2017-02-15 11:05:45 +00:00
|
|
|
// We haven't calculated a state for this event yet.
|
|
|
|
// Lets calculate one.
|
2022-02-23 15:41:32 +00:00
|
|
|
err = r.calculateAndSetState(ctx, input, roomInfo, &stateAtEvent, event, isRejected)
|
2022-01-27 14:29:14 +00:00
|
|
|
if err != nil {
|
2022-02-23 15:41:32 +00:00
|
|
|
return fmt.Errorf("r.calculateAndSetState: %w", err)
|
2017-09-20 09:59:19 +00:00
|
|
|
}
|
2017-02-15 11:05:45 +00:00
|
|
|
}
|
|
|
|
|
2022-08-22 09:30:35 +00:00
|
|
|
// We stop here if the event is rejected: We've stored it but won't update
|
|
|
|
// forward extremities or notify downstream components about it.
|
|
|
|
switch {
|
|
|
|
case isRejected:
|
|
|
|
logger.WithError(rejectionErr).Warn("Stored rejected event")
|
|
|
|
if rejectionErr != nil {
|
|
|
|
return types.RejectedError(rejectionErr.Error())
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
|
|
|
|
case softfail:
|
|
|
|
logger.WithError(rejectionErr).Warn("Stored soft-failed event")
|
2022-02-07 19:10:01 +00:00
|
|
|
if rejectionErr != nil {
|
2022-02-23 15:41:32 +00:00
|
|
|
return types.RejectedError(rejectionErr.Error())
|
2022-02-07 19:10:01 +00:00
|
|
|
}
|
2022-02-23 15:41:32 +00:00
|
|
|
return nil
|
2020-09-16 12:00:52 +00:00
|
|
|
}
|
|
|
|
|
2020-10-19 13:59:13 +00: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 14:11:10 +00:00
|
|
|
historyVisibility, // the history visibility before the event
|
2020-10-19 13:59:13 +00:00
|
|
|
); err != nil {
|
2022-02-23 15:41:32 +00:00
|
|
|
return fmt.Errorf("r.updateLatestEvents: %w", err)
|
2020-10-19 13:59:13 +00:00
|
|
|
}
|
|
|
|
case api.KindOld:
|
2022-07-01 09:54:07 +00:00
|
|
|
err = r.OutputProducer.ProduceRoomEvents(event.RoomID(), []api.OutputEvent{
|
2020-10-19 13:59:13 +00:00
|
|
|
{
|
|
|
|
Type: api.OutputTypeOldRoomEvent,
|
|
|
|
OldRoomEvent: &api.OutputOldRoomEvent{
|
2022-06-13 14:11:10 +00:00
|
|
|
Event: headered,
|
|
|
|
HistoryVisibility: historyVisibility,
|
2020-10-19 13:59:13 +00:00
|
|
|
},
|
|
|
|
},
|
|
|
|
})
|
|
|
|
if err != nil {
|
2022-02-23 15:41:32 +00:00
|
|
|
return fmt.Errorf("r.WriteOutputEvents (old): %w", err)
|
2020-10-19 13:59:13 +00:00
|
|
|
}
|
2020-05-18 16:49:24 +00:00
|
|
|
}
|
|
|
|
|
2022-11-14 12:07:13 +00:00
|
|
|
// Handle remote room upgrades, e.g. remove published room
|
|
|
|
if event.Type() == "m.room.tombstone" && event.StateKeyEquals("") && !r.Cfg.Matrix.IsLocalServerName(senderDomain) {
|
|
|
|
if err = r.handleRemoteRoomUpgrade(ctx, event); err != nil {
|
|
|
|
return fmt.Errorf("failed to handle remote room upgrade: %w", err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-07-07 11:51:55 +00: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 09:54:07 +00:00
|
|
|
err = r.OutputProducer.ProduceRoomEvents(event.RoomID(), []api.OutputEvent{
|
2020-07-07 11:51:55 +00:00
|
|
|
{
|
|
|
|
Type: api.OutputTypeRedactedEvent,
|
|
|
|
RedactedEvent: &api.OutputRedactedEvent{
|
|
|
|
RedactedEventID: redactedEventID,
|
|
|
|
RedactedBecause: redactionEvent.Headered(headered.RoomVersion),
|
|
|
|
},
|
|
|
|
},
|
|
|
|
})
|
|
|
|
if err != nil {
|
2022-02-23 15:41:32 +00:00
|
|
|
return fmt.Errorf("r.WriteOutputEvents (redactions): %w", err)
|
2020-07-07 11:51:55 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-12-22 12:05:59 +00:00
|
|
|
// If guest_access changed and is not can_join, kick all guest users.
|
|
|
|
if event.Type() == gomatrixserverlib.MRoomGuestAccess && gjson.GetBytes(event.Content(), "guest_access").Str != "can_join" {
|
|
|
|
if err = r.kickGuests(ctx, event, roomInfo); err != nil {
|
|
|
|
logrus.WithError(err).Error("failed to kick guest users on m.room.guest_access revocation")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-01-28 12:33:31 +00: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 15:41:32 +00:00
|
|
|
return nil
|
2018-05-26 11:03:35 +00:00
|
|
|
}
|
|
|
|
|
2022-11-14 12:07:13 +00:00
|
|
|
// handleRemoteRoomUpgrade updates published rooms and room aliases
|
|
|
|
func (r *Inputer) handleRemoteRoomUpgrade(ctx context.Context, event *gomatrixserverlib.Event) error {
|
|
|
|
oldRoomID := event.RoomID()
|
|
|
|
newRoomID := gjson.GetBytes(event.Content(), "replacement_room").Str
|
|
|
|
return r.DB.UpgradeRoom(ctx, oldRoomID, newRoomID, event.Sender())
|
|
|
|
}
|
|
|
|
|
2022-06-13 14:11:10 +00: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,
|
2023-03-01 16:06:47 +00:00
|
|
|
roomInfo *types.RoomInfo,
|
2022-06-13 14:11:10 +00:00
|
|
|
input *api.InputRoomEvent,
|
|
|
|
missingPrev bool,
|
|
|
|
) (historyVisibility gomatrixserverlib.HistoryVisibility, rejectionErr error, err error) {
|
2022-08-11 16:23:35 +00:00
|
|
|
historyVisibility = gomatrixserverlib.HistoryVisibilityShared // Default to shared.
|
2022-06-13 14:11:10 +00:00
|
|
|
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.
|
2023-03-01 16:06:47 +00:00
|
|
|
stateEvents, err := r.DB.EventsFromIDs(ctx, roomInfo, input.StateEventIDs)
|
2022-06-13 14:11:10 +00:00
|
|
|
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 14:29:14 +00: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.
|
2023-02-24 08:40:20 +00:00
|
|
|
// nolint: gocyclo
|
2022-01-27 14:29:14 +00:00
|
|
|
func (r *Inputer) fetchAuthEvents(
|
|
|
|
ctx context.Context,
|
|
|
|
logger *logrus.Entry,
|
2022-10-14 07:14:54 +00:00
|
|
|
roomInfo *types.RoomInfo,
|
2022-11-15 15:05:23 +00:00
|
|
|
virtualHost gomatrixserverlib.ServerName,
|
2022-01-27 14:29:14 +00:00
|
|
|
event *gomatrixserverlib.HeaderedEvent,
|
|
|
|
auth *gomatrixserverlib.AuthEvents,
|
|
|
|
known map[string]*types.Event,
|
|
|
|
servers []gomatrixserverlib.ServerName,
|
|
|
|
) error {
|
2022-06-07 13:23:26 +00:00
|
|
|
span, ctx := opentracing.StartSpanFromContext(ctx, "fetchAuthEvents")
|
|
|
|
defer span.Finish()
|
|
|
|
|
2022-01-27 14:29:14 +00:00
|
|
|
unknown := map[string]struct{}{}
|
|
|
|
authEventIDs := event.AuthEventIDs()
|
|
|
|
if len(authEventIDs) == 0 {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
for _, authEventID := range authEventIDs {
|
2023-03-01 16:06:47 +00:00
|
|
|
authEvents, err := r.DB.EventsFromIDs(ctx, roomInfo, []string{authEventID})
|
2022-01-27 14:29:14 +00:00
|
|
|
if err != nil || len(authEvents) == 0 || authEvents[0].Event == nil {
|
|
|
|
unknown[authEventID] = struct{}{}
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
ev := authEvents[0]
|
2022-10-14 07:14:54 +00:00
|
|
|
|
|
|
|
isRejected := false
|
|
|
|
if roomInfo != nil {
|
|
|
|
isRejected, err = r.DB.IsEventRejected(ctx, roomInfo.RoomNID, ev.EventID())
|
|
|
|
if err != nil && !errors.Is(err, sql.ErrNoRows) {
|
|
|
|
return fmt.Errorf("r.DB.IsEventRejected failed: %w", err)
|
|
|
|
}
|
|
|
|
}
|
2022-01-27 14:29:14 +00:00
|
|
|
known[authEventID] = &ev // don't take the pointer of the iterated event
|
2022-10-14 07:14:54 +00:00
|
|
|
if !isRejected {
|
|
|
|
if err = auth.AddEvent(ev.Event); err != nil {
|
|
|
|
return fmt.Errorf("auth.AddEvent: %w", err)
|
|
|
|
}
|
2022-01-27 14:29:14 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// 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.
|
2022-11-15 15:05:23 +00:00
|
|
|
res, err = r.FSAPI.GetEventAuth(ctx, virtualHost, serverName, event.RoomVersion, event.RoomID(), event.EventID())
|
2022-01-27 14:29:14 +00:00
|
|
|
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 17:06:13 +00:00
|
|
|
// Reuse these to reduce allocations.
|
|
|
|
authEventNIDs := make([]types.EventNID, 0, 5)
|
|
|
|
isRejected := false
|
|
|
|
nextAuthEvent:
|
2022-01-27 14:29:14 +00:00
|
|
|
for _, authEvent := range gomatrixserverlib.ReverseTopologicalOrdering(
|
2022-02-09 20:31:24 +00:00
|
|
|
res.AuthEvents.UntrustedEvents(event.RoomVersion),
|
2022-01-27 14:29:14 +00: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 17:06:13 +00:00
|
|
|
continue nextAuthEvent
|
2022-01-27 14:29:14 +00:00
|
|
|
}
|
|
|
|
|
2022-01-31 14:36:59 +00: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 14:29:14 +00:00
|
|
|
if err := authEvent.VerifyEventSignatures(ctx, r.FSAPI.KeyRing()); err != nil {
|
2022-02-08 17:06:13 +00:00
|
|
|
continue nextAuthEvent
|
2022-01-27 14:29:14 +00: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 17:06:13 +00:00
|
|
|
authEventNIDs = authEventNIDs[:0]
|
2022-01-27 14:29:14 +00:00
|
|
|
for _, eventID := range authEvent.AuthEventIDs() {
|
|
|
|
knownEvent, ok := known[eventID]
|
|
|
|
if !ok {
|
2022-02-08 17:06:13 +00:00
|
|
|
continue nextAuthEvent
|
2022-01-27 14:29:14 +00:00
|
|
|
}
|
|
|
|
authEventNIDs = append(authEventNIDs, knownEvent.EventNID)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Check if the auth event should be rejected.
|
2022-02-08 17:06:13 +00:00
|
|
|
err := gomatrixserverlib.Allowed(authEvent, auth)
|
|
|
|
if isRejected = err != nil; isRejected {
|
2022-01-27 14:29:14 +00:00
|
|
|
logger.WithError(err).Warnf("Auth event %s rejected", authEvent.EventID())
|
|
|
|
}
|
|
|
|
|
2023-03-01 16:06:47 +00:00
|
|
|
if roomInfo == nil {
|
|
|
|
roomInfo, err = r.DB.GetOrCreateRoomInfo(ctx, authEvent)
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("r.DB.GetOrCreateRoomInfo: %w", err)
|
|
|
|
}
|
2023-02-24 08:40:20 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
eventTypeNID, err := r.DB.GetOrCreateEventTypeNID(ctx, authEvent.Type())
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("r.DB.GetOrCreateEventTypeNID: %w", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
eventStateKeyNID, err := r.DB.GetOrCreateEventStateKeyNID(ctx, event.StateKey())
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("r.DB.GetOrCreateEventStateKeyNID: %w", err)
|
|
|
|
}
|
|
|
|
|
2022-01-27 14:29:14 +00:00
|
|
|
// Finally, store the event in the database.
|
2023-03-01 16:06:47 +00:00
|
|
|
eventNID, _, err := r.DB.StoreEvent(ctx, authEvent, roomInfo, eventTypeNID, eventStateKeyNID, authEventNIDs, isRejected)
|
2022-01-27 14:29:14 +00:00
|
|
|
if err != nil {
|
2022-02-04 10:39:34 +00:00
|
|
|
return fmt.Errorf("updater.StoreEvent: %w", err)
|
2022-01-27 14:29:14 +00:00
|
|
|
}
|
|
|
|
|
2022-02-08 17:06:13 +00: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 14:29:14 +00: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 16:13:15 +00:00
|
|
|
func (r *Inputer) calculateAndSetState(
|
2018-05-26 11:03:35 +00:00
|
|
|
ctx context.Context,
|
2020-09-03 14:22:16 +00:00
|
|
|
input *api.InputRoomEvent,
|
2022-01-27 14:29:14 +00:00
|
|
|
roomInfo *types.RoomInfo,
|
2018-05-26 11:03:35 +00:00
|
|
|
stateAtEvent *types.StateAtEvent,
|
2020-11-16 15:44:53 +00:00
|
|
|
event *gomatrixserverlib.Event,
|
2020-09-16 12:00:52 +00:00
|
|
|
isRejected bool,
|
2018-05-26 11:03:35 +00:00
|
|
|
) error {
|
2022-06-07 13:23:26 +00:00
|
|
|
span, ctx := opentracing.StartSpanFromContext(ctx, "calculateAndSetState")
|
|
|
|
defer span.Finish()
|
|
|
|
|
2022-02-23 15:41:32 +00: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 10:39:34 +00:00
|
|
|
roomState := state.NewStateResolution(updater, roomInfo)
|
2020-02-05 16:25:58 +00:00
|
|
|
|
2022-01-31 14:36:59 +00:00
|
|
|
if input.HasState {
|
2018-05-26 11:03:35 +00: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-08-18 16:06:13 +00:00
|
|
|
if entries, err = r.DB.StateEntriesForEventIDs(ctx, input.StateEventIDs, true); err != nil {
|
2022-02-04 10:39:34 +00:00
|
|
|
return fmt.Errorf("updater.StateEntriesForEventIDs: %w", err)
|
2018-05-26 11:03:35 +00:00
|
|
|
}
|
2020-09-15 10:17:46 +00:00
|
|
|
entries = types.DeduplicateStateEntries(entries)
|
2018-05-26 11:03:35 +00:00
|
|
|
|
2022-02-04 10:39:34 +00:00
|
|
|
if stateAtEvent.BeforeStateSnapshotNID, err = updater.AddState(ctx, roomInfo.RoomNID, nil, entries); err != nil {
|
|
|
|
return fmt.Errorf("updater.AddState: %w", err)
|
2018-05-26 11:03:35 +00: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 12:00:52 +00:00
|
|
|
if stateAtEvent.BeforeStateSnapshotNID, err = roomState.CalculateAndStoreStateBeforeEvent(ctx, event, isRejected); err != nil {
|
2020-09-15 10:17:46 +00:00
|
|
|
return fmt.Errorf("roomState.CalculateAndStoreStateBeforeEvent: %w", err)
|
2018-05-26 11:03:35 +00:00
|
|
|
}
|
|
|
|
}
|
2020-09-15 10:17:46 +00:00
|
|
|
|
2022-02-04 10:39:34 +00:00
|
|
|
err = updater.SetState(ctx, stateAtEvent.EventNID, stateAtEvent.BeforeStateSnapshotNID)
|
2020-09-15 10:17:46 +00:00
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("r.DB.SetState: %w", err)
|
|
|
|
}
|
2022-02-23 15:41:32 +00:00
|
|
|
succeeded = true
|
2020-09-15 10:17:46 +00:00
|
|
|
return nil
|
2017-08-21 15:37:11 +00:00
|
|
|
}
|
2022-12-22 12:05:59 +00:00
|
|
|
|
|
|
|
// kickGuests kicks guests users from m.room.guest_access rooms, if guest access is now prohibited.
|
|
|
|
func (r *Inputer) kickGuests(ctx context.Context, event *gomatrixserverlib.Event, roomInfo *types.RoomInfo) error {
|
|
|
|
membershipNIDs, err := r.DB.GetMembershipEventNIDsForRoom(ctx, roomInfo.RoomNID, true, true)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2023-03-01 16:06:47 +00:00
|
|
|
memberEvents, err := r.DB.Events(ctx, roomInfo, membershipNIDs)
|
2022-12-22 12:05:59 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
inputEvents := make([]api.InputRoomEvent, 0, len(memberEvents))
|
|
|
|
latestReq := &api.QueryLatestEventsAndStateRequest{
|
|
|
|
RoomID: event.RoomID(),
|
|
|
|
}
|
|
|
|
latestRes := &api.QueryLatestEventsAndStateResponse{}
|
|
|
|
if err = r.Queryer.QueryLatestEventsAndState(ctx, latestReq, latestRes); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
prevEvents := latestRes.LatestEvents
|
|
|
|
for _, memberEvent := range memberEvents {
|
|
|
|
if memberEvent.StateKey() == nil {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
localpart, senderDomain, err := gomatrixserverlib.SplitID('@', *memberEvent.StateKey())
|
|
|
|
if err != nil {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
accountRes := &userAPI.QueryAccountByLocalpartResponse{}
|
|
|
|
if err = r.UserAPI.QueryAccountByLocalpart(ctx, &userAPI.QueryAccountByLocalpartRequest{
|
|
|
|
Localpart: localpart,
|
|
|
|
ServerName: senderDomain,
|
|
|
|
}, accountRes); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
if accountRes.Account == nil {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
if accountRes.Account.AccountType != userAPI.AccountTypeGuest {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
var memberContent gomatrixserverlib.MemberContent
|
|
|
|
if err = json.Unmarshal(memberEvent.Content(), &memberContent); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
memberContent.Membership = gomatrixserverlib.Leave
|
|
|
|
|
|
|
|
stateKey := *memberEvent.StateKey()
|
|
|
|
fledglingEvent := &gomatrixserverlib.EventBuilder{
|
|
|
|
RoomID: event.RoomID(),
|
|
|
|
Type: gomatrixserverlib.MRoomMember,
|
|
|
|
StateKey: &stateKey,
|
|
|
|
Sender: stateKey,
|
|
|
|
PrevEvents: prevEvents,
|
|
|
|
}
|
|
|
|
|
|
|
|
if fledglingEvent.Content, err = json.Marshal(memberContent); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
eventsNeeded, err := gomatrixserverlib.StateNeededForEventBuilder(fledglingEvent)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
event, err := eventutil.BuildEvent(ctx, fledglingEvent, r.Cfg.Matrix, r.SigningIdentity, time.Now(), &eventsNeeded, latestRes)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
inputEvents = append(inputEvents, api.InputRoomEvent{
|
|
|
|
Kind: api.KindNew,
|
|
|
|
Event: event,
|
|
|
|
Origin: senderDomain,
|
|
|
|
SendAsServer: string(senderDomain),
|
|
|
|
})
|
|
|
|
prevEvents = []gomatrixserverlib.EventReference{
|
|
|
|
event.EventReference(),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
inputReq := &api.InputRoomEventsRequest{
|
|
|
|
InputRoomEvents: inputEvents,
|
|
|
|
Asynchronous: true, // Needs to be async, as we otherwise create a deadlock
|
|
|
|
}
|
|
|
|
inputRes := &api.InputRoomEventsResponse{}
|
|
|
|
return r.InputRoomEvents(ctx, inputReq, inputRes)
|
|
|
|
}
|