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"
|
|
|
|
|
2022-10-14 07:14:54 +00:00
|
|
|
"github.com/matrix-org/gomatrixserverlib"
|
2023-04-06 08:55:01 +00:00
|
|
|
"github.com/matrix-org/gomatrixserverlib/fclient"
|
2023-04-19 14:50:33 +00:00
|
|
|
"github.com/matrix-org/gomatrixserverlib/spec"
|
2022-10-14 07:14:54 +00:00
|
|
|
"github.com/matrix-org/util"
|
|
|
|
"github.com/prometheus/client_golang/prometheus"
|
|
|
|
"github.com/sirupsen/logrus"
|
|
|
|
|
2023-03-03 13:03:17 +00:00
|
|
|
"github.com/matrix-org/dendrite/roomserver/internal/helpers"
|
|
|
|
|
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,
|
2023-04-19 14:50:33 +00:00
|
|
|
virtualHost spec.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:
|
|
|
|
}
|
|
|
|
|
2023-03-13 15:45:14 +00:00
|
|
|
trace, ctx := internal.StartRegion(ctx, "processRoomEvent")
|
|
|
|
trace.SetTag("room_id", input.Event.RoomID())
|
|
|
|
trace.SetTag("event_id", input.Event.EventID())
|
|
|
|
defer trace.EndRegion()
|
2022-06-07 13:23:26 +00:00
|
|
|
|
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
|
2023-05-02 14:03:16 +00:00
|
|
|
event := headered.PDU
|
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)
|
|
|
|
}
|
2023-04-19 14:50:33 +00:00
|
|
|
isCreateEvent := event.Type() == spec.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
|
|
|
}
|
2023-06-14 14:23:46 +00:00
|
|
|
validRoomID, err := spec.NewRoomID(event.RoomID())
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
sender, err := r.Queryer.QueryUserIDForSender(ctx, *validRoomID, event.SenderID())
|
2022-09-26 16:35:35 +00:00
|
|
|
if err != nil {
|
2023-06-06 20:55:18 +00:00
|
|
|
return fmt.Errorf("failed getting userID for sender %q. %w", event.SenderID(), err)
|
|
|
|
}
|
|
|
|
senderDomain := spec.ServerName("")
|
|
|
|
if sender != nil {
|
|
|
|
senderDomain = sender.Domain()
|
2022-09-26 16:35:35 +00:00
|
|
|
}
|
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.
|
2023-04-19 14:50:33 +00:00
|
|
|
servers := map[spec.ServerName]struct{}{}
|
2022-01-31 14:36:59 +00:00
|
|
|
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)
|
|
|
|
}
|
2023-06-06 20:55:18 +00:00
|
|
|
// Only perform this check if the sender mxid_mapping can be resolved.
|
|
|
|
// Don't fail processing the event if we have no mxid_maping.
|
|
|
|
if sender != nil && 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{},
|
2023-05-02 14:03:16 +00:00
|
|
|
haveEvents: map[string]gomatrixserverlib.PDU{},
|
2022-01-27 14:29:14 +00:00
|
|
|
}
|
2022-09-26 16:35:35 +00:00
|
|
|
var stateSnapshot *parsedRespState
|
2023-04-27 11:54:20 +00:00
|
|
|
if stateSnapshot, err = missingState.processEventWithMissingState(ctx, event, headered.Version()); 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-06-14 14:23:46 +00:00
|
|
|
if err = gomatrixserverlib.Allowed(event, &authEvents, func(roomID spec.RoomID, senderID spec.SenderID) (*spec.UserID, error) {
|
|
|
|
return r.Queryer.QueryUserIDForSender(ctx, roomID, senderID)
|
2023-06-06 20:55:18 +00:00
|
|
|
}); err != nil {
|
2023-01-20 14:18:06 +00:00
|
|
|
isRejected = true
|
|
|
|
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-06-14 14:23:46 +00:00
|
|
|
softfail, err = helpers.CheckForSoftFail(ctx, r.DB, roomInfo, headered, input.StateEventIDs, r.Queryer)
|
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-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
|
|
|
}
|
|
|
|
|
2023-03-03 13:03:17 +00:00
|
|
|
// if storing this event results in it being redacted then do so.
|
|
|
|
// we do this after calculating state for this event as we may need to get power levels
|
|
|
|
var (
|
|
|
|
redactedEventID string
|
2023-05-02 14:03:16 +00:00
|
|
|
redactionEvent gomatrixserverlib.PDU
|
|
|
|
redactedEvent gomatrixserverlib.PDU
|
2023-03-03 13:03:17 +00:00
|
|
|
)
|
|
|
|
if !isRejected && !isCreateEvent {
|
2023-06-14 14:23:46 +00:00
|
|
|
resolver := state.NewStateResolution(r.DB, roomInfo, r.Queryer)
|
2023-06-28 18:29:49 +00:00
|
|
|
redactionEvent, redactedEvent, err = r.DB.MaybeRedactEvent(ctx, roomInfo, eventNID, event, &resolver, r.Queryer)
|
2023-03-03 13:03:17 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
if redactedEvent != nil {
|
|
|
|
redactedEventID = redactedEvent.EventID()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
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,
|
2023-05-02 14:03:16 +00:00
|
|
|
RedactedBecause: &types.HeaderedEvent{PDU: redactionEvent},
|
2020-07-07 11:51:55 +00:00
|
|
|
},
|
|
|
|
},
|
|
|
|
})
|
|
|
|
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.
|
2023-04-19 14:50:33 +00:00
|
|
|
if event.Type() == spec.MRoomGuestAccess && gjson.GetBytes(event.Content(), "guest_access").Str != "can_join" {
|
2023-04-27 06:07:13 +00:00
|
|
|
if err = r.kickGuests(ctx, event, roomInfo); err != nil && err != sql.ErrNoRows {
|
2022-12-22 12:05:59 +00:00
|
|
|
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
|
2023-05-02 14:03:16 +00:00
|
|
|
func (r *Inputer) handleRemoteRoomUpgrade(ctx context.Context, event gomatrixserverlib.PDU) error {
|
2022-11-14 12:07:13 +00:00
|
|
|
oldRoomID := event.RoomID()
|
|
|
|
newRoomID := gjson.GetBytes(event.Content(), "replacement_room").Str
|
2023-06-07 17:14:35 +00:00
|
|
|
return r.DB.UpgradeRoom(ctx, oldRoomID, newRoomID, string(event.SenderID()))
|
2022-11-14 12:07:13 +00:00
|
|
|
}
|
|
|
|
|
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.
|
2023-05-02 14:03:16 +00:00
|
|
|
event := input.Event.PDU
|
2023-04-19 14:50:33 +00:00
|
|
|
isCreateEvent := event.Type() == spec.MRoomCreate && event.StateKeyEquals("")
|
2023-05-02 14:03:16 +00:00
|
|
|
var stateBeforeEvent []gomatrixserverlib.PDU
|
2022-06-13 14:11:10 +00:00
|
|
|
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)
|
|
|
|
}
|
2023-05-02 14:03:16 +00:00
|
|
|
stateBeforeEvent = make([]gomatrixserverlib.PDU, 0, len(stateEvents))
|
2022-06-13 14:11:10 +00:00
|
|
|
for _, entry := range stateEvents {
|
2023-05-02 14:03:16 +00:00
|
|
|
stateBeforeEvent = append(stateBeforeEvent, entry.PDU)
|
2022-06-13 14:11:10 +00:00
|
|
|
}
|
|
|
|
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.
|
2023-04-27 15:35:19 +00:00
|
|
|
tuplesNeeded := gomatrixserverlib.StateNeededForAuth([]gomatrixserverlib.PDU{event}).Tuples()
|
2022-06-13 14:11:10 +00:00
|
|
|
tuplesNeeded = append(tuplesNeeded, gomatrixserverlib.StateKeyTuple{
|
2023-04-19 14:50:33 +00:00
|
|
|
EventType: spec.MRoomHistoryVisibility,
|
2022-06-13 14:11:10 +00:00
|
|
|
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:
|
2023-05-02 14:03:16 +00:00
|
|
|
stateBeforeEvent = make([]gomatrixserverlib.PDU, len(stateBeforeRes.StateEvents))
|
2023-04-27 11:54:20 +00:00
|
|
|
for i := range stateBeforeRes.StateEvents {
|
2023-05-02 14:03:16 +00:00
|
|
|
stateBeforeEvent[i] = stateBeforeRes.StateEvents[i].PDU
|
2023-04-27 11:54:20 +00:00
|
|
|
}
|
2022-06-13 14:11:10 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
// 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.
|
2023-04-27 15:35:19 +00:00
|
|
|
stateBeforeAuth := gomatrixserverlib.NewAuthEvents(
|
|
|
|
gomatrixserverlib.ToPDUs(stateBeforeEvent),
|
|
|
|
)
|
2023-06-14 14:23:46 +00:00
|
|
|
if rejectionErr = gomatrixserverlib.Allowed(event, &stateBeforeAuth, func(roomID spec.RoomID, senderID spec.SenderID) (*spec.UserID, error) {
|
|
|
|
return r.Queryer.QueryUserIDForSender(ctx, roomID, senderID)
|
2023-06-06 20:55:18 +00:00
|
|
|
}); rejectionErr != nil {
|
2023-04-27 11:54:20 +00:00
|
|
|
rejectionErr = fmt.Errorf("Allowed() failed for stateBeforeEvent: %w", rejectionErr)
|
2022-06-13 14:11:10 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
// Work out what the history visibility was at the time of the
|
|
|
|
// event.
|
|
|
|
for _, event := range stateBeforeEvent {
|
2023-04-19 14:50:33 +00:00
|
|
|
if event.Type() != spec.MRoomHistoryVisibility || !event.StateKeyEquals("") {
|
2022-06-13 14:11:10 +00:00
|
|
|
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,
|
2023-04-19 14:50:33 +00:00
|
|
|
virtualHost spec.ServerName,
|
2023-04-27 11:54:20 +00:00
|
|
|
event *types.HeaderedEvent,
|
2022-01-27 14:29:14 +00:00
|
|
|
auth *gomatrixserverlib.AuthEvents,
|
|
|
|
known map[string]*types.Event,
|
2023-04-19 14:50:33 +00:00
|
|
|
servers []spec.ServerName,
|
2022-01-27 14:29:14 +00:00
|
|
|
) error {
|
2023-03-13 15:45:14 +00:00
|
|
|
trace, ctx := internal.StartRegion(ctx, "fetchAuthEvents")
|
|
|
|
defer trace.EndRegion()
|
2022-06-07 13:23:26 +00:00
|
|
|
|
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})
|
2023-05-02 14:03:16 +00:00
|
|
|
if err != nil || len(authEvents) == 0 || authEvents[0].PDU == nil {
|
2022-01-27 14:29:14 +00:00
|
|
|
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 {
|
2023-05-02 14:03:16 +00:00
|
|
|
if err = auth.AddEvent(ev.PDU); err != nil {
|
2022-10-14 07:14:54 +00:00
|
|
|
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
|
2023-04-06 08:55:01 +00:00
|
|
|
var res fclient.RespEventAuth
|
2022-01-27 14:29:14 +00:00
|
|
|
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.
|
2023-04-27 11:54:20 +00:00
|
|
|
res, err = r.FSAPI.GetEventAuth(ctx, virtualHost, serverName, event.Version(), 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(
|
2023-04-27 15:35:19 +00:00
|
|
|
gomatrixserverlib.ToPDUs(res.AuthEvents.UntrustedEvents(event.Version())),
|
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.
|
2023-06-14 14:23:46 +00:00
|
|
|
if err := gomatrixserverlib.VerifyEventSignatures(ctx, authEvent, r.FSAPI.KeyRing(), func(roomID spec.RoomID, senderID spec.SenderID) (*spec.UserID, error) {
|
|
|
|
return r.Queryer.QueryUserIDForSender(ctx, roomID, senderID)
|
2023-06-06 20:55:18 +00:00
|
|
|
}); 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.
|
2023-06-14 14:23:46 +00:00
|
|
|
err := gomatrixserverlib.Allowed(authEvent, auth, func(roomID spec.RoomID, senderID spec.SenderID) (*spec.UserID, error) {
|
|
|
|
return r.Queryer.QueryUserIDForSender(ctx, roomID, senderID)
|
2023-06-06 20:55:18 +00:00
|
|
|
})
|
2022-02-08 17:06:13 +00:00
|
|
|
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,
|
2023-05-02 14:03:16 +00:00
|
|
|
PDU: authEvent,
|
2022-01-27 14:29:14 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
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,
|
2023-05-02 14:03:16 +00:00
|
|
|
event gomatrixserverlib.PDU,
|
2020-09-16 12:00:52 +00:00
|
|
|
isRejected bool,
|
2018-05-26 11:03:35 +00:00
|
|
|
) error {
|
2023-03-13 15:45:14 +00:00
|
|
|
trace, ctx := internal.StartRegion(ctx, "calculateAndSetState")
|
|
|
|
defer trace.EndRegion()
|
2022-06-07 13:23:26 +00:00
|
|
|
|
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)
|
2023-06-14 14:23:46 +00:00
|
|
|
roomState := state.NewStateResolution(updater, roomInfo, r.Queryer)
|
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.
|
2023-05-02 14:03:16 +00:00
|
|
|
func (r *Inputer) kickGuests(ctx context.Context, event gomatrixserverlib.PDU, roomInfo *types.RoomInfo) error {
|
2022-12-22 12:05:59 +00:00
|
|
|
membershipNIDs, err := r.DB.GetMembershipEventNIDsForRoom(ctx, roomInfo.RoomNID, true, true)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2023-05-08 19:25:44 +00:00
|
|
|
if roomInfo == nil {
|
|
|
|
return types.ErrorInvalidRoomInfo
|
|
|
|
}
|
|
|
|
memberEvents, err := r.DB.Events(ctx, roomInfo.RoomVersion, 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
|
|
|
|
}
|
|
|
|
|
2023-06-14 14:23:46 +00:00
|
|
|
validRoomID, err := spec.NewRoomID(event.RoomID())
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2022-12-22 12:05:59 +00:00
|
|
|
prevEvents := latestRes.LatestEvents
|
|
|
|
for _, memberEvent := range memberEvents {
|
|
|
|
if memberEvent.StateKey() == nil {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
2023-06-14 14:23:46 +00:00
|
|
|
memberUserID, err := r.Queryer.QueryUserIDForSender(ctx, *validRoomID, spec.SenderID(*memberEvent.StateKey()))
|
2022-12-22 12:05:59 +00:00
|
|
|
if err != nil {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
accountRes := &userAPI.QueryAccountByLocalpartResponse{}
|
|
|
|
if err = r.UserAPI.QueryAccountByLocalpart(ctx, &userAPI.QueryAccountByLocalpartRequest{
|
2023-06-12 11:19:25 +00:00
|
|
|
Localpart: memberUserID.Local(),
|
|
|
|
ServerName: memberUserID.Domain(),
|
2022-12-22 12:05:59 +00:00
|
|
|
}, 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
|
|
|
|
}
|
2023-04-19 14:50:33 +00:00
|
|
|
memberContent.Membership = spec.Leave
|
2022-12-22 12:05:59 +00:00
|
|
|
|
|
|
|
stateKey := *memberEvent.StateKey()
|
2023-05-04 10:17:42 +00:00
|
|
|
fledglingEvent := &gomatrixserverlib.ProtoEvent{
|
2022-12-22 12:05:59 +00:00
|
|
|
RoomID: event.RoomID(),
|
2023-04-19 14:50:33 +00:00
|
|
|
Type: spec.MRoomMember,
|
2022-12-22 12:05:59 +00:00
|
|
|
StateKey: &stateKey,
|
2023-06-07 17:14:35 +00:00
|
|
|
SenderID: stateKey,
|
2022-12-22 12:05:59 +00:00
|
|
|
PrevEvents: prevEvents,
|
|
|
|
}
|
|
|
|
|
|
|
|
if fledglingEvent.Content, err = json.Marshal(memberContent); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2023-05-04 10:17:42 +00:00
|
|
|
eventsNeeded, err := gomatrixserverlib.StateNeededForProtoEvent(fledglingEvent)
|
2022-12-22 12:05:59 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2023-06-28 18:29:49 +00:00
|
|
|
validRoomID, err := spec.NewRoomID(event.RoomID())
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
userID, err := spec.NewUserID(stateKey, true)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
signingIdentity, err := r.SigningIdentity(ctx, *validRoomID, *userID)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
event, err := eventutil.BuildEvent(ctx, fledglingEvent, &signingIdentity, time.Now(), &eventsNeeded, latestRes)
|
2022-12-22 12:05:59 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
inputEvents = append(inputEvents, api.InputRoomEvent{
|
|
|
|
Kind: api.KindNew,
|
|
|
|
Event: event,
|
2023-06-12 11:19:25 +00:00
|
|
|
Origin: memberUserID.Domain(),
|
|
|
|
SendAsServer: string(memberUserID.Domain()),
|
2022-12-22 12:05:59 +00:00
|
|
|
})
|
2023-05-24 10:14:42 +00:00
|
|
|
prevEvents = []string{event.EventID()}
|
2022-12-22 12:05:59 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
inputReq := &api.InputRoomEventsRequest{
|
|
|
|
InputRoomEvents: inputEvents,
|
|
|
|
Asynchronous: true, // Needs to be async, as we otherwise create a deadlock
|
|
|
|
}
|
|
|
|
inputRes := &api.InputRoomEventsResponse{}
|
2023-05-09 22:46:49 +00:00
|
|
|
r.InputRoomEvents(ctx, inputReq, inputRes)
|
|
|
|
return nil
|
2022-12-22 12:05:59 +00:00
|
|
|
}
|