Implement new RoomVersionImpl API (#3062)

As outlined in https://github.com/matrix-org/gomatrixserverlib/pull/368

The main change Dendrite side is that `RoomVersion` no longer has any
methods on it. Instead, you need to bounce via `gmsl.GetRoomVersion`.

It's very interesting to see where exactly Dendrite cares about this.
For some places it's creating events (fine) but others are way more
specific. Those areas will need to migrate to GMSL at some point.
This commit is contained in:
kegsay 2023-04-21 17:06:29 +01:00 committed by GitHub
parent 71eeccf34a
commit 1647213fac
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
25 changed files with 144 additions and 65 deletions

View file

@ -321,7 +321,7 @@ func TestRoomsV3URLEscapeDoNot404(t *testing.T) {
) )
for _, tc := range testCases { for _, tc := range testCases {
ev, err := tc.roomVer.NewEventFromTrustedJSON([]byte(tc.eventJSON), false) ev, err := gomatrixserverlib.MustGetRoomVersion(tc.roomVer).NewEventFromTrustedJSON([]byte(tc.eventJSON), false)
if err != nil { if err != nil {
t.Errorf("failed to parse event: %s", err) t.Errorf("failed to parse event: %s", err)
} }

View file

@ -201,8 +201,9 @@ func (r *FederationInternalAPI) performJoinUsingServer(
if respMakeJoin.RoomVersion == "" { if respMakeJoin.RoomVersion == "" {
respMakeJoin.RoomVersion = setDefaultRoomVersionFromJoinEvent(respMakeJoin.JoinEvent) respMakeJoin.RoomVersion = setDefaultRoomVersionFromJoinEvent(respMakeJoin.JoinEvent)
} }
if _, err = respMakeJoin.RoomVersion.EventFormat(); err != nil { verImpl, err := gomatrixserverlib.GetRoomVersion(respMakeJoin.RoomVersion)
return fmt.Errorf("respMakeJoin.RoomVersion.EventFormat: %w", err) if err != nil {
return err
} }
// Build the join event. // Build the join event.
@ -235,7 +236,7 @@ func (r *FederationInternalAPI) performJoinUsingServer(
// contain signatures that we don't know about. // contain signatures that we don't know about.
if len(respSendJoin.Event) > 0 { if len(respSendJoin.Event) > 0 {
var remoteEvent *gomatrixserverlib.Event var remoteEvent *gomatrixserverlib.Event
remoteEvent, err = respMakeJoin.RoomVersion.NewEventFromUntrustedJSON(respSendJoin.Event) remoteEvent, err = verImpl.NewEventFromUntrustedJSON(respSendJoin.Event)
if err == nil && isWellFormedMembershipEvent( if err == nil && isWellFormedMembershipEvent(
remoteEvent, roomID, userID, remoteEvent, roomID, userID,
) { ) {
@ -464,8 +465,8 @@ func (r *FederationInternalAPI) performOutboundPeekUsingServer(
if respPeek.RoomVersion == "" { if respPeek.RoomVersion == "" {
respPeek.RoomVersion = gomatrixserverlib.RoomVersionV1 respPeek.RoomVersion = gomatrixserverlib.RoomVersionV1
} }
if _, err = respPeek.RoomVersion.EventFormat(); err != nil { if !gomatrixserverlib.KnownRoomVersion(respPeek.RoomVersion) {
return fmt.Errorf("respPeek.RoomVersion.EventFormat: %w", err) return fmt.Errorf("unknown room version: %s", respPeek.RoomVersion)
} }
// we have the peek state now so let's process regardless of whether upstream gives up // we have the peek state now so let's process regardless of whether upstream gives up
@ -552,6 +553,13 @@ func (r *FederationInternalAPI) PerformLeave(
continue continue
} }
// Work out if we support the room version that has been supplied in
// the make_leave response.
_, err = gomatrixserverlib.GetRoomVersion(respMakeLeave.RoomVersion)
if err != nil {
return err
}
// Set all the fields to be what they should be, this should be a no-op // Set all the fields to be what they should be, this should be a no-op
// but it's possible that the remote server returned us something "odd" // but it's possible that the remote server returned us something "odd"
respMakeLeave.LeaveEvent.Type = spec.MRoomMember respMakeLeave.LeaveEvent.Type = spec.MRoomMember
@ -573,12 +581,6 @@ func (r *FederationInternalAPI) PerformLeave(
continue continue
} }
// Work out if we support the room version that has been supplied in
// the make_leave response.
if _, err = respMakeLeave.RoomVersion.EventFormat(); err != nil {
return gomatrixserverlib.UnsupportedRoomVersionError{}
}
// Build the leave event. // Build the leave event.
event, err := respMakeLeave.LeaveEvent.Build( event, err := respMakeLeave.LeaveEvent.Build(
time.Now(), time.Now(),
@ -659,8 +661,12 @@ func (r *FederationInternalAPI) PerformInvite(
if err != nil { if err != nil {
return fmt.Errorf("r.federation.SendInviteV2: failed to send invite: %w", err) return fmt.Errorf("r.federation.SendInviteV2: failed to send invite: %w", err)
} }
verImpl, err := gomatrixserverlib.GetRoomVersion(request.RoomVersion)
if err != nil {
return err
}
inviteEvent, err := request.RoomVersion.NewEventFromUntrustedJSON(inviteRes.Event) inviteEvent, err := verImpl.NewEventFromUntrustedJSON(inviteRes.Event)
if err != nil { if err != nil {
return fmt.Errorf("r.federation.SendInviteV2 failed to decode event response: %w", err) return fmt.Errorf("r.federation.SendInviteV2 failed to decode event response: %w", err)
} }
@ -779,6 +785,10 @@ func federatedAuthProvider(
// to repeat the entire set of checks just for a missing event or two. // to repeat the entire set of checks just for a missing event or two.
return func(roomVersion gomatrixserverlib.RoomVersion, eventIDs []string) ([]*gomatrixserverlib.Event, error) { return func(roomVersion gomatrixserverlib.RoomVersion, eventIDs []string) ([]*gomatrixserverlib.Event, error) {
returning := []*gomatrixserverlib.Event{} returning := []*gomatrixserverlib.Event{}
verImpl, err := gomatrixserverlib.GetRoomVersion(roomVersion)
if err != nil {
return nil, err
}
// See if we have retry entries for each of the supplied event IDs. // See if we have retry entries for each of the supplied event IDs.
for _, eventID := range eventIDs { for _, eventID := range eventIDs {
@ -808,7 +818,7 @@ func federatedAuthProvider(
// event ID again. // event ID again.
for _, pdu := range tx.PDUs { for _, pdu := range tx.PDUs {
// Try to parse the event. // Try to parse the event.
ev, everr := roomVersion.NewEventFromUntrustedJSON(pdu) ev, everr := verImpl.NewEventFromUntrustedJSON(pdu)
if everr != nil { if everr != nil {
return nil, fmt.Errorf("missingAuth gomatrixserverlib.NewEventFromUntrustedJSON: %w", everr) return nil, fmt.Errorf("missingAuth gomatrixserverlib.NewEventFromUntrustedJSON: %w", everr)
} }

View file

@ -105,7 +105,7 @@ func (f *stubFederationClient) P2PSendTransactionToRelay(ctx context.Context, u
func mustCreatePDU(t *testing.T) *gomatrixserverlib.HeaderedEvent { func mustCreatePDU(t *testing.T) *gomatrixserverlib.HeaderedEvent {
t.Helper() t.Helper()
content := `{"type":"m.room.message"}` content := `{"type":"m.room.message"}`
ev, err := gomatrixserverlib.RoomVersionV10.NewEventFromTrustedJSON([]byte(content), false) ev, err := gomatrixserverlib.MustGetRoomVersion(gomatrixserverlib.RoomVersionV10).NewEventFromTrustedJSON([]byte(content), false)
if err != nil { if err != nil {
t.Fatalf("failed to create event: %v", err) t.Fatalf("failed to create event: %v", err)
} }

View file

@ -22,7 +22,6 @@ import (
"github.com/matrix-org/dendrite/clientapi/jsonerror" "github.com/matrix-org/dendrite/clientapi/jsonerror"
"github.com/matrix-org/dendrite/roomserver/api" "github.com/matrix-org/dendrite/roomserver/api"
roomserverVersion "github.com/matrix-org/dendrite/roomserver/version"
"github.com/matrix-org/dendrite/setup/config" "github.com/matrix-org/dendrite/setup/config"
"github.com/matrix-org/gomatrixserverlib" "github.com/matrix-org/gomatrixserverlib"
"github.com/matrix-org/gomatrixserverlib/fclient" "github.com/matrix-org/gomatrixserverlib/fclient"
@ -78,7 +77,7 @@ func InviteV1(
) util.JSONResponse { ) util.JSONResponse {
roomVer := gomatrixserverlib.RoomVersionV1 roomVer := gomatrixserverlib.RoomVersionV1
body := request.Content() body := request.Content()
event, err := roomVer.NewEventFromTrustedJSON(body, false) event, err := gomatrixserverlib.MustGetRoomVersion(roomVer).NewEventFromTrustedJSON(body, false)
switch err.(type) { switch err.(type) {
case gomatrixserverlib.BadJSONError: case gomatrixserverlib.BadJSONError:
return util.JSONResponse{ return util.JSONResponse{
@ -116,7 +115,8 @@ func processInvite(
) util.JSONResponse { ) util.JSONResponse {
// Check that we can accept invites for this room version. // Check that we can accept invites for this room version.
if _, err := roomserverVersion.SupportedRoomVersion(roomVer); err != nil { verImpl, err := gomatrixserverlib.GetRoomVersion(roomVer)
if err != nil {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
JSON: jsonerror.UnsupportedRoomVersion( JSON: jsonerror.UnsupportedRoomVersion(
@ -157,7 +157,7 @@ func processInvite(
} }
// Check that the event is signed by the server sending the request. // Check that the event is signed by the server sending the request.
redacted, err := event.Version().RedactEventJSON(event.JSON()) redacted, err := verImpl.RedactEventJSON(event.JSON())
if err != nil { if err != nil {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,

View file

@ -206,8 +206,17 @@ func SendJoin(
JSON: jsonerror.InternalServerError(), JSON: jsonerror.InternalServerError(),
} }
} }
verImpl, err := gomatrixserverlib.GetRoomVersion(verRes.RoomVersion)
if err != nil {
return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: jsonerror.UnsupportedRoomVersion(
fmt.Sprintf("QueryRoomVersionForRoom returned unknown room version: %s", verRes.RoomVersion),
),
}
}
event, err := verRes.RoomVersion.NewEventFromUntrustedJSON(request.Content()) event, err := verImpl.NewEventFromUntrustedJSON(request.Content())
if err != nil { if err != nil {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
@ -287,7 +296,7 @@ func SendJoin(
} }
// Check that the event is signed by the server sending the request. // Check that the event is signed by the server sending the request.
redacted, err := event.Version().RedactEventJSON(event.JSON()) redacted, err := verImpl.RedactEventJSON(event.JSON())
if err != nil { if err != nil {
logrus.WithError(err).Errorf("XXX: join.go") logrus.WithError(err).Errorf("XXX: join.go")
return util.JSONResponse{ return util.JSONResponse{
@ -461,9 +470,11 @@ func checkRestrictedJoin(
roomVersion gomatrixserverlib.RoomVersion, roomVersion gomatrixserverlib.RoomVersion,
roomID, userID string, roomID, userID string,
) (*util.JSONResponse, string, error) { ) (*util.JSONResponse, string, error) {
if allowRestricted, err := roomVersion.MayAllowRestrictedJoinsInEventAuth(); err != nil { verImpl, err := gomatrixserverlib.GetRoomVersion(roomVersion)
if err != nil {
return nil, "", err return nil, "", err
} else if !allowRestricted { }
if !verImpl.MayAllowRestrictedJoinsInEventAuth() {
return nil, "", nil return nil, "", nil
} }
req := &api.QueryRestrictedJoinAllowedRequest{ req := &api.QueryRestrictedJoinAllowedRequest{

View file

@ -149,8 +149,18 @@ func SendLeave(
} }
} }
verImpl, err := gomatrixserverlib.GetRoomVersion(verRes.RoomVersion)
if err != nil {
return util.JSONResponse{
Code: http.StatusInternalServerError,
JSON: jsonerror.UnsupportedRoomVersion(
fmt.Sprintf("QueryRoomVersionForRoom returned unknown version: %s", verRes.RoomVersion),
),
}
}
// Decode the event JSON from the request. // Decode the event JSON from the request.
event, err := verRes.RoomVersion.NewEventFromUntrustedJSON(request.Content()) event, err := verImpl.NewEventFromUntrustedJSON(request.Content())
switch err.(type) { switch err.(type) {
case gomatrixserverlib.BadJSONError: case gomatrixserverlib.BadJSONError:
return util.JSONResponse{ return util.JSONResponse{
@ -253,7 +263,7 @@ func SendLeave(
} }
// Check that the event is signed by the server sending the request. // Check that the event is signed by the server sending the request.
redacted, err := event.Version().RedactEventJSON(event.JSON()) redacted, err := verImpl.RedactEventJSON(event.JSON())
if err != nil { if err != nil {
logrus.WithError(err).Errorf("XXX: leave.go") logrus.WithError(err).Errorf("XXX: leave.go")
return util.JSONResponse{ return util.JSONResponse{

View file

@ -196,7 +196,12 @@ func ExchangeThirdPartyInvite(
util.GetLogger(httpReq.Context()).WithError(err).Error("federation.SendInvite failed") util.GetLogger(httpReq.Context()).WithError(err).Error("federation.SendInvite failed")
return jsonerror.InternalServerError() return jsonerror.InternalServerError()
} }
inviteEvent, err := verRes.RoomVersion.NewEventFromUntrustedJSON(signedEvent.Event) verImpl, err := gomatrixserverlib.GetRoomVersion(verRes.RoomVersion)
if err != nil {
util.GetLogger(httpReq.Context()).WithError(err).Errorf("unknown room version: %s", verRes.RoomVersion)
return jsonerror.InternalServerError()
}
inviteEvent, err := verImpl.NewEventFromUntrustedJSON(signedEvent.Event)
if err != nil { if err != nil {
util.GetLogger(httpReq.Context()).WithError(err).Error("federation.SendInvite failed") util.GetLogger(httpReq.Context()).WithError(err).Error("federation.SendInvite failed")
return jsonerror.InternalServerError() return jsonerror.InternalServerError()

2
go.mod
View file

@ -22,7 +22,7 @@ require (
github.com/matrix-org/dugong v0.0.0-20210921133753-66e6b1c67e2e github.com/matrix-org/dugong v0.0.0-20210921133753-66e6b1c67e2e
github.com/matrix-org/go-sqlite3-js v0.0.0-20220419092513-28aa791a1c91 github.com/matrix-org/go-sqlite3-js v0.0.0-20220419092513-28aa791a1c91
github.com/matrix-org/gomatrix v0.0.0-20220926102614-ceba4d9f7530 github.com/matrix-org/gomatrix v0.0.0-20220926102614-ceba4d9f7530
github.com/matrix-org/gomatrixserverlib v0.0.0-20230420172450-7ea8ead4a832 github.com/matrix-org/gomatrixserverlib v0.0.0-20230421153744-40a91492619e
github.com/matrix-org/pinecone v0.11.1-0.20230210171230-8c3b24f2649a github.com/matrix-org/pinecone v0.11.1-0.20230210171230-8c3b24f2649a
github.com/matrix-org/util v0.0.0-20221111132719-399730281e66 github.com/matrix-org/util v0.0.0-20221111132719-399730281e66
github.com/mattn/go-sqlite3 v1.14.16 github.com/mattn/go-sqlite3 v1.14.16

6
go.sum
View file

@ -337,6 +337,12 @@ github.com/matrix-org/gomatrixserverlib v0.0.0-20230420165305-c51ffd14d28d h1:pS
github.com/matrix-org/gomatrixserverlib v0.0.0-20230420165305-c51ffd14d28d/go.mod h1:7HTbSZe+CIdmeqVyFMekwD5dFU8khWQyngKATvd12FU= github.com/matrix-org/gomatrixserverlib v0.0.0-20230420165305-c51ffd14d28d/go.mod h1:7HTbSZe+CIdmeqVyFMekwD5dFU8khWQyngKATvd12FU=
github.com/matrix-org/gomatrixserverlib v0.0.0-20230420172450-7ea8ead4a832 h1:xEUPCS8+BEJ9+JEazxkQS1+YnWyFAsHoIMp5ijA7NAY= github.com/matrix-org/gomatrixserverlib v0.0.0-20230420172450-7ea8ead4a832 h1:xEUPCS8+BEJ9+JEazxkQS1+YnWyFAsHoIMp5ijA7NAY=
github.com/matrix-org/gomatrixserverlib v0.0.0-20230420172450-7ea8ead4a832/go.mod h1:7HTbSZe+CIdmeqVyFMekwD5dFU8khWQyngKATvd12FU= github.com/matrix-org/gomatrixserverlib v0.0.0-20230420172450-7ea8ead4a832/go.mod h1:7HTbSZe+CIdmeqVyFMekwD5dFU8khWQyngKATvd12FU=
github.com/matrix-org/gomatrixserverlib v0.0.0-20230421103805-98f1fbf26443 h1:UxYdP/B+wN67pOWpvzlNeASMn9K1reF/bPHFo1wpqXQ=
github.com/matrix-org/gomatrixserverlib v0.0.0-20230421103805-98f1fbf26443/go.mod h1:7HTbSZe+CIdmeqVyFMekwD5dFU8khWQyngKATvd12FU=
github.com/matrix-org/gomatrixserverlib v0.0.0-20230421152946-4e6e880889e3 h1:+svc0Md8R2SYlcJu45NR+/JO1aYzMrMAi7rGLS1UfsM=
github.com/matrix-org/gomatrixserverlib v0.0.0-20230421152946-4e6e880889e3/go.mod h1:7HTbSZe+CIdmeqVyFMekwD5dFU8khWQyngKATvd12FU=
github.com/matrix-org/gomatrixserverlib v0.0.0-20230421153744-40a91492619e h1:lGhoTgpiLYPkVIAHOW/7itugzkLWs81tNlpHI6bhT5I=
github.com/matrix-org/gomatrixserverlib v0.0.0-20230421153744-40a91492619e/go.mod h1:7HTbSZe+CIdmeqVyFMekwD5dFU8khWQyngKATvd12FU=
github.com/matrix-org/pinecone v0.11.1-0.20230210171230-8c3b24f2649a h1:awrPDf9LEFySxTLKYBMCiObelNx/cBuv/wzllvCCH3A= github.com/matrix-org/pinecone v0.11.1-0.20230210171230-8c3b24f2649a h1:awrPDf9LEFySxTLKYBMCiObelNx/cBuv/wzllvCCH3A=
github.com/matrix-org/pinecone v0.11.1-0.20230210171230-8c3b24f2649a/go.mod h1:HchJX9oKMXaT2xYFs0Ha/6Zs06mxLU8k6F1ODnrGkeQ= github.com/matrix-org/pinecone v0.11.1-0.20230210171230-8c3b24f2649a/go.mod h1:HchJX9oKMXaT2xYFs0Ha/6Zs06mxLU8k6F1ODnrGkeQ=
github.com/matrix-org/util v0.0.0-20221111132719-399730281e66 h1:6z4KxomXSIGWqhHcfzExgkH3Z3UkIXry4ibJS4Aqz2Y= github.com/matrix-org/util v0.0.0-20221111132719-399730281e66 h1:6z4KxomXSIGWqhHcfzExgkH3Z3UkIXry4ibJS4Aqz2Y=

View file

@ -112,10 +112,11 @@ func addPrevEventsToEvent(
return ErrRoomNoExists return ErrRoomNoExists
} }
eventFormat, err := queryRes.RoomVersion.EventFormat() verImpl, err := gomatrixserverlib.GetRoomVersion(queryRes.RoomVersion)
if err != nil { if err != nil {
return fmt.Errorf("queryRes.RoomVersion.EventFormat: %w", err) return fmt.Errorf("GetRoomVersion: %w", err)
} }
eventFormat := verImpl.EventFormat()
builder.Depth = queryRes.Depth builder.Depth = queryRes.Depth

View file

@ -189,7 +189,7 @@ func TestPatternMatches(t *testing.T) {
} }
func mustEventFromJSON(t *testing.T, json string) *gomatrixserverlib.Event { func mustEventFromJSON(t *testing.T, json string) *gomatrixserverlib.Event {
ev, err := gomatrixserverlib.RoomVersionV7.NewEventFromTrustedJSON([]byte(json), false) ev, err := gomatrixserverlib.MustGetRoomVersion(gomatrixserverlib.RoomVersionV7).NewEventFromTrustedJSON([]byte(json), false)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }

View file

@ -137,7 +137,11 @@ func (t *TxnReq) ProcessTransaction(ctx context.Context) (*fclient.RespSend, *ut
continue continue
} }
roomVersion := getRoomVersion(header.RoomID) roomVersion := getRoomVersion(header.RoomID)
event, err := roomVersion.NewEventFromUntrustedJSON(pdu) verImpl, err := gomatrixserverlib.GetRoomVersion(roomVersion)
if err != nil {
continue
}
event, err := verImpl.NewEventFromUntrustedJSON(pdu)
if err != nil { if err != nil {
if _, ok := err.(gomatrixserverlib.BadJSONError); ok { if _, ok := err.(gomatrixserverlib.BadJSONError); ok {
// Room version 6 states that homeservers should strictly enforce canonical JSON // Room version 6 states that homeservers should strictly enforce canonical JSON

View file

@ -633,7 +633,7 @@ func TestProcessTransactionRequestEDUUnhandled(t *testing.T) {
func init() { func init() {
for _, j := range testData { for _, j := range testData {
e, err := testRoomVersion.NewEventFromTrustedJSON(j, false) e, err := gomatrixserverlib.MustGetRoomVersion(testRoomVersion).NewEventFromTrustedJSON(j, false)
if err != nil { if err != nil {
panic("cannot load test data: " + err.Error()) panic("cannot load test data: " + err.Error())
} }

View file

@ -149,7 +149,12 @@ func IsInvitePending(
return false, "", "", nil, fmt.Errorf("missing user for NID %d (%+v)", senderUserNIDs[0], senderUsers) return false, "", "", nil, fmt.Errorf("missing user for NID %d (%+v)", senderUserNIDs[0], senderUsers)
} }
event, err := info.RoomVersion.NewEventFromTrustedJSON(eventJSON, false) verImpl, err := gomatrixserverlib.GetRoomVersion(info.RoomVersion)
if err != nil {
return false, "", "", nil, err
}
event, err := verImpl.NewEventFromTrustedJSON(eventJSON, false)
return true, senderUser, userNIDToEventID[senderUserNIDs[0]], event, err return true, senderUser, userNIDToEventID[senderUserNIDs[0]], event, err
} }

View file

@ -838,6 +838,11 @@ func (t *missingStateReq) lookupEvent(ctx context.Context, roomVersion gomatrixs
trace, ctx := internal.StartRegion(ctx, "lookupEvent") trace, ctx := internal.StartRegion(ctx, "lookupEvent")
defer trace.EndRegion() defer trace.EndRegion()
verImpl, err := gomatrixserverlib.GetRoomVersion(roomVersion)
if err != nil {
return nil, err
}
if localFirst { if localFirst {
// fetch from the roomserver // fetch from the roomserver
events, err := t.db.EventsFromIDs(ctx, t.roomInfo, []string{missingEventID}) events, err := t.db.EventsFromIDs(ctx, t.roomInfo, []string{missingEventID})
@ -865,7 +870,7 @@ func (t *missingStateReq) lookupEvent(ctx context.Context, roomVersion gomatrixs
} }
continue continue
} }
event, err = roomVersion.NewEventFromUntrustedJSON(txn.PDUs[0]) event, err = verImpl.NewEventFromUntrustedJSON(txn.PDUs[0])
if err != nil { if err != nil {
t.log.WithError(err).WithField("missing_event_id", missingEventID).Warnf("Failed to parse event JSON of event returned from /event") t.log.WithError(err).WithField("missing_event_id", missingEventID).Warnf("Failed to parse event JSON of event returned from /event")
continue continue

View file

@ -35,7 +35,7 @@ func TestSingleTransactionOnInput(t *testing.T) {
ctx, cancel := context.WithDeadline(processCtx.Context(), deadline) ctx, cancel := context.WithDeadline(processCtx.Context(), deadline)
defer cancel() defer cancel()
event, err := gomatrixserverlib.RoomVersionV6.NewEventFromTrustedJSON( event, err := gomatrixserverlib.MustGetRoomVersion(gomatrixserverlib.RoomVersionV6).NewEventFromTrustedJSON(
[]byte(`{"auth_events":[],"content":{"creator":"@neilalexander:dendrite.matrix.org","room_version":"6"},"depth":1,"hashes":{"sha256":"jqOqdNEH5r0NiN3xJtj0u5XUVmRqq9YvGbki1wxxuuM"},"origin":"dendrite.matrix.org","origin_server_ts":1644595362726,"prev_events":[],"prev_state":[],"room_id":"!jSZZRknA6GkTBXNP:dendrite.matrix.org","sender":"@neilalexander:dendrite.matrix.org","signatures":{"dendrite.matrix.org":{"ed25519:6jB2aB":"bsQXO1wketf1OSe9xlndDIWe71W9KIundc6rBw4KEZdGPW7x4Tv4zDWWvbxDsG64sS2IPWfIm+J0OOozbrWIDw"}},"state_key":"","type":"m.room.create"}`), []byte(`{"auth_events":[],"content":{"creator":"@neilalexander:dendrite.matrix.org","room_version":"6"},"depth":1,"hashes":{"sha256":"jqOqdNEH5r0NiN3xJtj0u5XUVmRqq9YvGbki1wxxuuM"},"origin":"dendrite.matrix.org","origin_server_ts":1644595362726,"prev_events":[],"prev_state":[],"room_id":"!jSZZRknA6GkTBXNP:dendrite.matrix.org","sender":"@neilalexander:dendrite.matrix.org","signatures":{"dendrite.matrix.org":{"ed25519:6jB2aB":"bsQXO1wketf1OSe9xlndDIWe71W9KIundc6rBw4KEZdGPW7x4Tv4zDWWvbxDsG64sS2IPWfIm+J0OOozbrWIDw"}},"state_key":"","type":"m.room.create"}`),
false, false,
) )

View file

@ -884,12 +884,14 @@ func (r *Queryer) QueryRestrictedJoinAllowed(ctx context.Context, req *api.Query
if roomInfo == nil || roomInfo.IsStub() { if roomInfo == nil || roomInfo.IsStub() {
return nil // fmt.Errorf("room %q doesn't exist or is stub room", req.RoomID) return nil // fmt.Errorf("room %q doesn't exist or is stub room", req.RoomID)
} }
verImpl, err := gomatrixserverlib.GetRoomVersion(roomInfo.RoomVersion)
if err != nil {
return err
}
// If the room version doesn't allow restricted joins then don't // If the room version doesn't allow restricted joins then don't
// try to process any further. // try to process any further.
allowRestrictedJoins, err := roomInfo.RoomVersion.MayAllowRestrictedJoinsInEventAuth() allowRestrictedJoins := verImpl.MayAllowRestrictedJoinsInEventAuth()
if err != nil { if !allowRestrictedJoins {
return fmt.Errorf("roomInfo.RoomVersion.AllowRestrictedJoinsInEventAuth: %w", err)
} else if !allowRestrictedJoins {
return nil return nil
} }
// Start off by populating the "resident" flag in the response. If we // Start off by populating the "resident" flag in the response. If we

View file

@ -54,7 +54,7 @@ func (db *getEventDB) addFakeEvent(eventID string, authIDs []string) error {
return err return err
} }
event, err := gomatrixserverlib.RoomVersionV1.NewEventFromTrustedJSON( event, err := gomatrixserverlib.MustGetRoomVersion(gomatrixserverlib.RoomVersionV1).NewEventFromTrustedJSON(
eventJSON, false, eventJSON, false,
) )
if err != nil { if err != nil {

View file

@ -878,10 +878,12 @@ func (v *StateResolution) resolveConflicts(
trace, ctx := internal.StartRegion(ctx, "StateResolution.resolveConflicts") trace, ctx := internal.StartRegion(ctx, "StateResolution.resolveConflicts")
defer trace.EndRegion() defer trace.EndRegion()
stateResAlgo, err := version.StateResAlgorithm() verImpl, err := gomatrixserverlib.GetRoomVersion(version)
if err != nil { if err != nil {
return nil, err return nil, err
} }
stateResAlgo := verImpl.StateResAlgorithm()
switch stateResAlgo { switch stateResAlgo {
case gomatrixserverlib.StateResV1: case gomatrixserverlib.StateResV1:
return v.resolveConflictsV1(ctx, notConflicted, conflicted) return v.resolveConflictsV1(ctx, notConflicted, conflicted)

View file

@ -218,6 +218,10 @@ func (s *stateSnapshotStatements) BulkSelectMembershipForHistoryVisibility(
var membershipEventID string var membershipEventID string
knownEvents := make(map[string]*gomatrixserverlib.HeaderedEvent, len(eventIDs)) knownEvents := make(map[string]*gomatrixserverlib.HeaderedEvent, len(eventIDs))
verImpl, err := gomatrixserverlib.GetRoomVersion(roomInfo.RoomVersion)
if err != nil {
return nil, err
}
for rows.Next() { for rows.Next() {
if err = rows.Scan(&eventID, &membershipEventID, &evJson); err != nil { if err = rows.Scan(&eventID, &membershipEventID, &evJson); err != nil {
@ -232,7 +236,7 @@ func (s *stateSnapshotStatements) BulkSelectMembershipForHistoryVisibility(
result[eventID] = ev result[eventID] = ev
continue continue
} }
event, err := roomInfo.RoomVersion.NewEventFromTrustedJSON(evJson, false) event, err := verImpl.NewEventFromTrustedJSON(evJson, false)
if err != nil { if err != nil {
result[eventID] = &gomatrixserverlib.HeaderedEvent{} result[eventID] = &gomatrixserverlib.HeaderedEvent{}
// not fatal // not fatal

View file

@ -579,9 +579,14 @@ func (d *EventDatabase) events(
eventIDs = map[types.EventNID]string{} eventIDs = map[types.EventNID]string{}
} }
verImpl, err := gomatrixserverlib.GetRoomVersion(roomInfo.RoomVersion)
if err != nil {
return nil, err
}
for _, eventJSON := range eventJSONs { for _, eventJSON := range eventJSONs {
redacted := gjson.GetBytes(eventJSON.EventJSON, "unsigned.redacted_because").Exists() redacted := gjson.GetBytes(eventJSON.EventJSON, "unsigned.redacted_because").Exists()
events[eventJSON.EventNID], err = roomInfo.RoomVersion.NewEventFromTrustedJSONWithEventID( events[eventJSON.EventNID], err = verImpl.NewEventFromTrustedJSONWithEventID(
eventIDs[eventJSON.EventNID], eventJSON.EventJSON, redacted, eventIDs[eventJSON.EventNID], eventJSON.EventJSON, redacted,
) )
if err != nil { if err != nil {
@ -1125,13 +1130,17 @@ func (d *Database) GetHistoryVisibilityState(ctx context.Context, roomInfo *type
if err != nil { if err != nil {
eventIDs = map[types.EventNID]string{} eventIDs = map[types.EventNID]string{}
} }
verImpl, err := gomatrixserverlib.GetRoomVersion(roomInfo.RoomVersion)
if err != nil {
return nil, err
}
events := make([]*gomatrixserverlib.Event, 0, len(eventNIDs)) events := make([]*gomatrixserverlib.Event, 0, len(eventNIDs))
for _, eventNID := range eventNIDs { for _, eventNID := range eventNIDs {
data, err := d.EventJSONTable.BulkSelectEventJSON(ctx, nil, []types.EventNID{eventNID}) data, err := d.EventJSONTable.BulkSelectEventJSON(ctx, nil, []types.EventNID{eventNID})
if err != nil { if err != nil {
return nil, err return nil, err
} }
ev, err := roomInfo.RoomVersion.NewEventFromTrustedJSONWithEventID(eventIDs[eventNID], data[0].EventJSON, false) ev, err := verImpl.NewEventFromTrustedJSONWithEventID(eventIDs[eventNID], data[0].EventJSON, false)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -1181,6 +1190,10 @@ func (d *Database) GetStateEvent(ctx context.Context, roomID, evType, stateKey s
eventNIDs = append(eventNIDs, e.EventNID) eventNIDs = append(eventNIDs, e.EventNID)
} }
} }
verImpl, err := gomatrixserverlib.GetRoomVersion(roomInfo.RoomVersion)
if err != nil {
return nil, err
}
eventIDs, _ := d.EventsTable.BulkSelectEventID(ctx, nil, eventNIDs) eventIDs, _ := d.EventsTable.BulkSelectEventID(ctx, nil, eventNIDs)
if err != nil { if err != nil {
eventIDs = map[types.EventNID]string{} eventIDs = map[types.EventNID]string{}
@ -1195,7 +1208,7 @@ func (d *Database) GetStateEvent(ctx context.Context, roomID, evType, stateKey s
if len(data) == 0 { if len(data) == 0 {
return nil, fmt.Errorf("GetStateEvent: no json for event nid %d", e.EventNID) return nil, fmt.Errorf("GetStateEvent: no json for event nid %d", e.EventNID)
} }
ev, err := roomInfo.RoomVersion.NewEventFromTrustedJSONWithEventID(eventIDs[e.EventNID], data[0].EventJSON, false) ev, err := verImpl.NewEventFromTrustedJSONWithEventID(eventIDs[e.EventNID], data[0].EventJSON, false)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -1250,9 +1263,13 @@ func (d *Database) GetStateEventsWithEventType(ctx context.Context, roomID, evTy
if len(eventPairs) == 0 { if len(eventPairs) == 0 {
return nil, nil return nil, nil
} }
verImpl, err := gomatrixserverlib.GetRoomVersion(roomInfo.RoomVersion)
if err != nil {
return nil, err
}
var result []*gomatrixserverlib.HeaderedEvent var result []*gomatrixserverlib.HeaderedEvent
for _, pair := range eventPairs { for _, pair := range eventPairs {
ev, err := roomInfo.RoomVersion.NewEventFromTrustedJSONWithEventID(eventIDs[pair.EventNID], pair.EventJSON, false) ev, err := verImpl.NewEventFromTrustedJSONWithEventID(eventIDs[pair.EventNID], pair.EventJSON, false)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -1372,7 +1389,11 @@ func (d *Database) GetBulkStateContent(ctx context.Context, roomIDs []string, tu
result := make([]tables.StrippedEvent, len(events)) result := make([]tables.StrippedEvent, len(events))
for i := range events { for i := range events {
roomVer := eventNIDToVer[events[i].EventNID] roomVer := eventNIDToVer[events[i].EventNID]
ev, err := roomVer.NewEventFromTrustedJSONWithEventID(eventIDs[events[i].EventNID], events[i].EventJSON, false) verImpl, err := gomatrixserverlib.GetRoomVersion(roomVer)
if err != nil {
return nil, err
}
ev, err := verImpl.NewEventFromTrustedJSONWithEventID(eventIDs[events[i].EventNID], events[i].EventJSON, false)
if err != nil { if err != nil {
return nil, fmt.Errorf("GetBulkStateContent: failed to load event JSON for event NID %v : %w", events[i].EventNID, err) return nil, fmt.Errorf("GetBulkStateContent: failed to load event JSON for event NID %v : %w", events[i].EventNID, err)
} }

View file

@ -28,39 +28,32 @@ func DefaultRoomVersion() gomatrixserverlib.RoomVersion {
// RoomVersions returns a map of all known room versions to this // RoomVersions returns a map of all known room versions to this
// server. // server.
func RoomVersions() map[gomatrixserverlib.RoomVersion]gomatrixserverlib.RoomVersionDescription { func RoomVersions() map[gomatrixserverlib.RoomVersion]gomatrixserverlib.RoomVersionImpl {
return gomatrixserverlib.RoomVersions() return gomatrixserverlib.RoomVersions()
} }
// SupportedRoomVersions returns a map of descriptions for room // SupportedRoomVersions returns a map of descriptions for room
// versions that are supported by this homeserver. // versions that are supported by this homeserver.
func SupportedRoomVersions() map[gomatrixserverlib.RoomVersion]gomatrixserverlib.RoomVersionDescription { func SupportedRoomVersions() map[gomatrixserverlib.RoomVersion]gomatrixserverlib.RoomVersionImpl {
return gomatrixserverlib.SupportedRoomVersions() return gomatrixserverlib.RoomVersions()
} }
// RoomVersion returns information about a specific room version. // RoomVersion returns information about a specific room version.
// An UnknownVersionError is returned if the version is not known // An UnknownVersionError is returned if the version is not known
// to the server. // to the server.
func RoomVersion(version gomatrixserverlib.RoomVersion) (gomatrixserverlib.RoomVersionDescription, error) { func RoomVersion(version gomatrixserverlib.RoomVersion) (gomatrixserverlib.RoomVersionImpl, error) {
if version, ok := gomatrixserverlib.RoomVersions()[version]; ok { if version, ok := gomatrixserverlib.RoomVersions()[version]; ok {
return version, nil return version, nil
} }
return gomatrixserverlib.RoomVersionDescription{}, UnknownVersionError{version} return gomatrixserverlib.RoomVersionImpl{}, UnknownVersionError{version}
} }
// SupportedRoomVersion returns information about a specific room // SupportedRoomVersion returns information about a specific room
// version. An UnknownVersionError is returned if the version is not // version. An UnknownVersionError is returned if the version is not
// known to the server, or an UnsupportedVersionError is returned if // known to the server, or an UnsupportedVersionError is returned if
// the version is known but specifically marked as unsupported. // the version is known but specifically marked as unsupported.
func SupportedRoomVersion(version gomatrixserverlib.RoomVersion) (gomatrixserverlib.RoomVersionDescription, error) { func SupportedRoomVersion(version gomatrixserverlib.RoomVersion) (gomatrixserverlib.RoomVersionImpl, error) {
result, err := RoomVersion(version) return RoomVersion(version)
if err != nil {
return gomatrixserverlib.RoomVersionDescription{}, err
}
if !result.Supported {
return gomatrixserverlib.RoomVersionDescription{}, UnsupportedVersionError{version}
}
return result, nil
} }
// UnknownVersionError is caused when the room version is not known. // UnknownVersionError is caused when the room version is not known.

View file

@ -24,7 +24,7 @@ import (
) )
func TestToClientEvent(t *testing.T) { // nolint: gocyclo func TestToClientEvent(t *testing.T) { // nolint: gocyclo
ev, err := gomatrixserverlib.RoomVersionV1.NewEventFromTrustedJSON([]byte(`{ ev, err := gomatrixserverlib.MustGetRoomVersion(gomatrixserverlib.RoomVersionV1).NewEventFromTrustedJSON([]byte(`{
"type": "m.room.name", "type": "m.room.name",
"state_key": "", "state_key": "",
"event_id": "$test:localhost", "event_id": "$test:localhost",
@ -79,7 +79,7 @@ func TestToClientEvent(t *testing.T) { // nolint: gocyclo
} }
func TestToClientFormatSync(t *testing.T) { func TestToClientFormatSync(t *testing.T) {
ev, err := gomatrixserverlib.RoomVersionV1.NewEventFromTrustedJSON([]byte(`{ ev, err := gomatrixserverlib.MustGetRoomVersion(gomatrixserverlib.RoomVersionV1).NewEventFromTrustedJSON([]byte(`{
"type": "m.room.name", "type": "m.room.name",
"state_key": "", "state_key": "",
"event_id": "$test:localhost", "event_id": "$test:localhost",

View file

@ -50,7 +50,7 @@ func TestNewInviteResponse(t *testing.T) {
event := `{"auth_events":["$SbSsh09j26UAXnjd3RZqf2lyA3Kw2sY_VZJVZQAV9yA","$EwL53onrLwQ5gL8Dv3VrOOCvHiueXu2ovLdzqkNi3lo","$l2wGmz9iAwevBDGpHT_xXLUA5O8BhORxWIGU1cGi1ZM","$GsWFJLXgdlF5HpZeyWkP72tzXYWW3uQ9X28HBuTztHE"],"content":{"avatar_url":"","displayname":"neilalexander","membership":"invite"},"depth":9,"hashes":{"sha256":"8p+Ur4f8vLFX6mkIXhxI0kegPG7X3tWy56QmvBkExAg"},"origin":"matrix.org","origin_server_ts":1602087113066,"prev_events":["$1v-O6tNwhOZcA8bvCYY-Dnj1V2ZDE58lLPxtlV97S28"],"prev_state":[],"room_id":"!XbeXirGWSPXbEaGokF:matrix.org","sender":"@neilalexander:matrix.org","signatures":{"dendrite.neilalexander.dev":{"ed25519:BMJi":"05KQ5lPw0cSFsE4A0x1z7vi/3cc8bG4WHUsFWYkhxvk/XkXMGIYAYkpNThIvSeLfdcHlbm/k10AsBSKH8Uq4DA"},"matrix.org":{"ed25519:a_RXGa":"jeovuHr9E/x0sHbFkdfxDDYV/EyoeLi98douZYqZ02iYddtKhfB7R3WLay/a+D3V3V7IW0FUmPh/A404x5sYCw"}},"state_key":"@neilalexander:dendrite.neilalexander.dev","type":"m.room.member","unsigned":{"age":2512,"invite_room_state":[{"content":{"join_rule":"invite"},"sender":"@neilalexander:matrix.org","state_key":"","type":"m.room.join_rules"},{"content":{"avatar_url":"mxc://matrix.org/BpDaozLwgLnlNStxDxvLzhPr","displayname":"neilalexander","membership":"join"},"sender":"@neilalexander:matrix.org","state_key":"@neilalexander:matrix.org","type":"m.room.member"},{"content":{"name":"Test room"},"sender":"@neilalexander:matrix.org","state_key":"","type":"m.room.name"}]},"_room_version":"5"}` event := `{"auth_events":["$SbSsh09j26UAXnjd3RZqf2lyA3Kw2sY_VZJVZQAV9yA","$EwL53onrLwQ5gL8Dv3VrOOCvHiueXu2ovLdzqkNi3lo","$l2wGmz9iAwevBDGpHT_xXLUA5O8BhORxWIGU1cGi1ZM","$GsWFJLXgdlF5HpZeyWkP72tzXYWW3uQ9X28HBuTztHE"],"content":{"avatar_url":"","displayname":"neilalexander","membership":"invite"},"depth":9,"hashes":{"sha256":"8p+Ur4f8vLFX6mkIXhxI0kegPG7X3tWy56QmvBkExAg"},"origin":"matrix.org","origin_server_ts":1602087113066,"prev_events":["$1v-O6tNwhOZcA8bvCYY-Dnj1V2ZDE58lLPxtlV97S28"],"prev_state":[],"room_id":"!XbeXirGWSPXbEaGokF:matrix.org","sender":"@neilalexander:matrix.org","signatures":{"dendrite.neilalexander.dev":{"ed25519:BMJi":"05KQ5lPw0cSFsE4A0x1z7vi/3cc8bG4WHUsFWYkhxvk/XkXMGIYAYkpNThIvSeLfdcHlbm/k10AsBSKH8Uq4DA"},"matrix.org":{"ed25519:a_RXGa":"jeovuHr9E/x0sHbFkdfxDDYV/EyoeLi98douZYqZ02iYddtKhfB7R3WLay/a+D3V3V7IW0FUmPh/A404x5sYCw"}},"state_key":"@neilalexander:dendrite.neilalexander.dev","type":"m.room.member","unsigned":{"age":2512,"invite_room_state":[{"content":{"join_rule":"invite"},"sender":"@neilalexander:matrix.org","state_key":"","type":"m.room.join_rules"},{"content":{"avatar_url":"mxc://matrix.org/BpDaozLwgLnlNStxDxvLzhPr","displayname":"neilalexander","membership":"join"},"sender":"@neilalexander:matrix.org","state_key":"@neilalexander:matrix.org","type":"m.room.member"},{"content":{"name":"Test room"},"sender":"@neilalexander:matrix.org","state_key":"","type":"m.room.name"}]},"_room_version":"5"}`
expected := `{"invite_state":{"events":[{"content":{"join_rule":"invite"},"sender":"@neilalexander:matrix.org","state_key":"","type":"m.room.join_rules"},{"content":{"avatar_url":"mxc://matrix.org/BpDaozLwgLnlNStxDxvLzhPr","displayname":"neilalexander","membership":"join"},"sender":"@neilalexander:matrix.org","state_key":"@neilalexander:matrix.org","type":"m.room.member"},{"content":{"name":"Test room"},"sender":"@neilalexander:matrix.org","state_key":"","type":"m.room.name"},{"content":{"avatar_url":"","displayname":"neilalexander","membership":"invite"},"event_id":"$GQmw8e8-26CQv1QuFoHBHpKF1hQj61Flg3kvv_v_XWs","origin_server_ts":1602087113066,"sender":"@neilalexander:matrix.org","state_key":"@neilalexander:dendrite.neilalexander.dev","type":"m.room.member"}]}}` expected := `{"invite_state":{"events":[{"content":{"join_rule":"invite"},"sender":"@neilalexander:matrix.org","state_key":"","type":"m.room.join_rules"},{"content":{"avatar_url":"mxc://matrix.org/BpDaozLwgLnlNStxDxvLzhPr","displayname":"neilalexander","membership":"join"},"sender":"@neilalexander:matrix.org","state_key":"@neilalexander:matrix.org","type":"m.room.member"},{"content":{"name":"Test room"},"sender":"@neilalexander:matrix.org","state_key":"","type":"m.room.name"},{"content":{"avatar_url":"","displayname":"neilalexander","membership":"invite"},"event_id":"$GQmw8e8-26CQv1QuFoHBHpKF1hQj61Flg3kvv_v_XWs","origin_server_ts":1602087113066,"sender":"@neilalexander:matrix.org","state_key":"@neilalexander:dendrite.neilalexander.dev","type":"m.room.member"}]}}`
ev, err := gomatrixserverlib.RoomVersionV5.NewEventFromTrustedJSON([]byte(event), false) ev, err := gomatrixserverlib.MustGetRoomVersion(gomatrixserverlib.RoomVersionV5).NewEventFromTrustedJSON([]byte(event), false)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }

View file

@ -36,7 +36,7 @@ func mustCreateDatabase(t *testing.T, dbType test.DBType) (storage.UserDatabase,
func mustCreateEvent(t *testing.T, content string) *gomatrixserverlib.HeaderedEvent { func mustCreateEvent(t *testing.T, content string) *gomatrixserverlib.HeaderedEvent {
t.Helper() t.Helper()
ev, err := gomatrixserverlib.RoomVersionV10.NewEventFromTrustedJSON([]byte(content), false) ev, err := gomatrixserverlib.MustGetRoomVersion(gomatrixserverlib.RoomVersionV10).NewEventFromTrustedJSON([]byte(content), false)
if err != nil { if err != nil {
t.Fatalf("failed to create event: %v", err) t.Fatalf("failed to create event: %v", err)
} }