Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add test ensuring that /make_join and /send_join are rejected during a partial join #432

Merged
merged 6 commits into from
Aug 8, 2022
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 31 additions & 16 deletions internal/federation/handle.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,37 +38,52 @@ func MakeJoinRequestsHandler(s *Server, w http.ResponseWriter, req *http.Request
return
}

makeJoinResp, err := MakeRespMakeJoin(s, room, userID)
if err != "" {
w.WriteHeader(500)
w.Write([]byte(err))
return
}

// Send it
res := map[string]interface{}{
"event": makeJoinResp.JoinEvent,
"room_version": makeJoinResp.RoomVersion,
}
w.WriteHeader(200)
b, _ := json.Marshal(res)
w.Write(b)
}

// MakeRespMakeJoin makes the response for a /make_join request, without verifying any signatures
// or dealing with HTTP responses itself.
func MakeRespMakeJoin(s *Server, room *ServerRoom, userID string) (resp gomatrixserverlib.RespMakeJoin, err string) {
// Generate a join event
builder := gomatrixserverlib.EventBuilder{
Sender: userID,
RoomID: roomID,
RoomID: room.RoomID,
Type: "m.room.member",
StateKey: &userID,
PrevEvents: []string{room.Timeline[len(room.Timeline)-1].EventID()},
Depth: room.Timeline[len(room.Timeline)-1].Depth() + 1,
}
err := builder.SetContent(map[string]interface{}{"membership": gomatrixserverlib.Join})
if err != nil {
w.WriteHeader(500)
w.Write([]byte("complement: HandleMakeSendJoinRequests make_join cannot set membership content: " + err.Error()))
err2 := builder.SetContent(map[string]interface{}{"membership": gomatrixserverlib.Join})
if err2 != nil {
err = "complement: HandleMakeSendJoinRequests make_join cannot set membership content: " + err2.Error()
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this isn't very go-like. Instead:

Suggested change
err = "complement: HandleMakeSendJoinRequests make_join cannot set membership content: " + err2.Error()
err = fmt.Errorf("make_join cannot set membership content: %w", err2)

(and add the complement: HandleMakeSendJoinRequests back in, well, HandleMakeSendJoinRequests)

... which also means you don't need to mess about with err2, because everything is an Error.

likewise below.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, good tool to have in the toolbox — I was really struggling with this part and knew that err2 had to be a silly workaround.

Let me know if you spot any other improvements I should make here

return
}
stateNeeded, err := gomatrixserverlib.StateNeededForEventBuilder(&builder)
if err != nil {
w.WriteHeader(500)
w.Write([]byte("complement: HandleMakeSendJoinRequests make_join cannot calculate auth_events: " + err.Error()))
stateNeeded, err2 := gomatrixserverlib.StateNeededForEventBuilder(&builder)
if err2 != nil {
err = "complement: HandleMakeSendJoinRequests make_join cannot calculate auth_events: " + err2.Error()
return
}
builder.AuthEvents = room.AuthEvents(stateNeeded)

// Send it
res := map[string]interface{}{
"event": builder,
"room_version": room.Version,
resp = gomatrixserverlib.RespMakeJoin{
RoomVersion: room.Version,
JoinEvent: builder,
}
w.WriteHeader(200)
b, _ := json.Marshal(res)
w.Write(b)
return
}

// SendJoinRequestsHandler is the http.Handler implementation for the send_join part of
Expand Down
122 changes: 122 additions & 0 deletions tests/federation_room_join_partial_state_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -806,6 +806,128 @@ func TestPartialStateJoin(t *testing.T) {
},
)
})

// when the server is in the middle of a partial state join, it should not accept
// /make_join because it can't give a full answer.
t.Run("DoesntAnswerMakeJoinDuringPartialJoin", func(t *testing.T) {
// In this test, we have 3 homeservers:
// hs1 (the server under test) with @alice:hs1
// This is the server that will be in the middle of a partial join.
// testServer1 (a Complement test server) with @bob:<server name>
// This is the server that created the room originally.
// testServer2 (another Complement test server) with @charlie:<server name>
// This is the server that will try to make a join via testServer1.
deployment := Deploy(t, b.BlueprintAlice)
defer deployment.Destroy(t)
alice := deployment.Client(t, "hs1", "@alice:hs1")

testServer1 := createTestServer(t, deployment)
cancel := testServer1.Listen()
defer cancel()
serverRoom := createTestRoom(t, testServer1, alice.GetDefaultRoomVersion(t))
roomID := serverRoom.RoomID
psjResult := beginPartialStateJoin(t, testServer1, serverRoom, alice)
defer psjResult.Destroy()

// The partial join is now in progress.
// Let's have a new test server rock up and ask to join the room by making a
// /make_join request.

testServer2 := createTestServer(t, deployment)
cancel2 := testServer2.Listen()
defer cancel2()

fedClient2 := testServer2.FederationClient(deployment)

// charlie sends a make_join
_, err := fedClient2.MakeJoin(context.Background(), "hs1", roomID, testServer2.UserID("charlie"), federation.SupportedRoomVersions())

if err == nil {
t.Errorf("MakeJoin returned 200, want 404")
} else if httpError, ok := err.(gomatrix.HTTPError); ok {
t.Logf("MakeJoin => %d/%s", httpError.Code, string(httpError.Contents))
if httpError.Code != 404 {
t.Errorf("expected 404, got %d", httpError.Code)
}
errcode := must.GetJSONFieldStr(t, httpError.Contents, "errcode")
if errcode != "M_NOT_FOUND" {
t.Errorf("errcode: got %s, want M_NOT_FOUND", errcode)
}
} else {
t.Errorf("MakeJoin: non-HTTPError: %v", err)
}
})

// when the server is in the middle of a partial state join, it should not accept
// /send_join because it can't give a full answer.
t.Run("DoesntAnswerSendJoinDuringPartialJoin", func(t *testing.T) {
// In this test, we have 3 homeservers:
// hs1 (the server under test) with @alice:hs1
// This is the server that will be in the middle of a partial join.
// testServer1 (a Complement test server) with @charlie:<server name>
// This is the server that will create the room originally.
// testServer2 (another Complement test server) with @daniel:<server name>
// This is the server that will try to join the room via hs2,
// but only after using hs1 to /make_join (as otherwise we have no way
// of being able to build a request to /send_join)
//
// We use a blueprint with two servers rather than using two test servers
// because Complement test servers can't send requests to each other
// (their names only resolve within docker containers)
deployment := Deploy(t, b.BlueprintAlice)
defer deployment.Destroy(t)
alice := deployment.Client(t, "hs1", "@alice:hs1")

testServer1 := createTestServer(t, deployment)
cancel := testServer1.Listen()
defer cancel()
serverRoom := createTestRoom(t, testServer1, alice.GetDefaultRoomVersion(t))
psjResult := beginPartialStateJoin(t, testServer1, serverRoom, alice)
defer psjResult.Destroy()

// hs1's partial join is now in progress.
// Let's have a test server rock up and ask to /send_join in the room via hs1.
// To do that, we need to /make_join first.
// Asking hs1 to /make_join won't work, because it should reject that request.
// To work around that, we /make_join via hs2.

testServer2 := createTestServer(t, deployment)
cancel2 := testServer2.Listen()
defer cancel2()

fedClient2 := testServer2.FederationClient(deployment)

// Manually /make_join via testServer1.
// This is permissible because testServer1 is fully joined to the room.
// We can't actually use /make_join because host.docker.internal doesn't resolve,
// so compute it without making any requests:
makeJoinResp, errs := federation.MakeRespMakeJoin(testServer1, serverRoom, testServer2.UserID("daniel"))
if errs != "" {
t.Fatalf("MakeRespMakeJoin failed : %s", errs)
}

// charlie then tries to /send_join via the homeserver under test
joinEvent, err := makeJoinResp.JoinEvent.Build(time.Now(), gomatrixserverlib.ServerName(testServer2.ServerName()), testServer2.KeyID, testServer2.Priv, makeJoinResp.RoomVersion)
must.NotError(t, "JoinEvent.Build", err)

// SendJoin should return a 404 because the homeserver under test has not
// finished its partial join.
_, err = fedClient2.SendJoin(context.Background(), "hs1", joinEvent)
if err == nil {
t.Errorf("SendJoin returned 200, want 404")
} else if httpError, ok := err.(gomatrix.HTTPError); ok {
t.Logf("SendJoin => %d/%s", httpError.Code, string(httpError.Contents))
if httpError.Code != 404 {
t.Errorf("expected 404, got %d", httpError.Code)
}
errcode := must.GetJSONFieldStr(t, httpError.Contents, "errcode")
if errcode != "M_NOT_FOUND" {
t.Errorf("errcode: got %s, want M_NOT_FOUND", errcode)
}
} else {
t.Errorf("SendJoin: non-HTTPError: %v", err)
}
})
}

// test reception of an event over federation during a resync
Expand Down