main.go 18.0 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
// Copyright 2017 Vector Creations Ltd
//
// 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.

package main

import (
18
	"encoding/json"
19 20 21 22 23 24 25
	"fmt"
	"net/http"
	"os"
	"os/exec"
	"path/filepath"
	"time"

26
	"github.com/matrix-org/dendrite/common/test"
27
	"github.com/matrix-org/dendrite/roomserver/api"
28 29 30 31 32
	"github.com/matrix-org/gomatrixserverlib"
)

var (
	// Path to where kafka is installed.
33
	kafkaDir = test.Defaulting(os.Getenv("KAFKA_DIR"), "kafka")
34
	// The URI the kafka zookeeper is listening on.
35
	zookeeperURI = test.Defaulting(os.Getenv("ZOOKEEPER_URI"), "localhost:2181")
36
	// The URI the kafka server is listening on.
37
	kafkaURI = test.Defaulting(os.Getenv("KAFKA_URIS"), "localhost:9092")
38
	// The address the syncserver should listen on.
39
	syncserverAddr = test.Defaulting(os.Getenv("SYNCSERVER_URI"), "localhost:9876")
40 41 42
	// How long to wait for the syncserver to write the expected output messages.
	// This needs to be high enough to account for the time it takes to create
	// the postgres database tables which can take a while on travis.
43
	timeoutString = test.Defaulting(os.Getenv("TIMEOUT"), "10s")
44
	// The name of maintenance database to connect to in order to create the test database.
45 46 47
	postgresDatabase = test.Defaulting(os.Getenv("POSTGRES_DATABASE"), "postgres")
	// Postgres docker container name (for running psql). If not set, psql must be in PATH.
	postgresContainerName = os.Getenv("POSTGRES_CONTAINER")
48
	// The name of the test database to create.
49
	testDatabaseName = test.Defaulting(os.Getenv("DATABASE_NAME"), "syncserver_test")
50
	// The postgres connection config for connecting to the test database.
51
	testDatabase = test.Defaulting(os.Getenv("DATABASE"), fmt.Sprintf("dbname=%s sslmode=disable binary_parameters=yes", testDatabaseName))
52 53 54 55
)

const inputTopic = "syncserverInput"

56 57 58 59 60 61 62 63 64
var exe = test.KafkaExecutor{
	ZookeeperURI:   zookeeperURI,
	KafkaDirectory: kafkaDir,
	KafkaURI:       kafkaURI,
	// Send stdout and stderr to our stderr so that we see error messages from
	// the kafka process.
	OutputWriter: os.Stderr,
}

65 66 67
var syncServerConfigFileContents = (`consumer_uris: ["` + kafkaURI + `"]
roomserver_topic: "` + inputTopic + `"
database: "` + testDatabase + `"
68
server_name: "localhost"
69 70 71
`)

var timeout time.Duration
72
var clientEventTestData []string
73 74 75 76 77 78 79

func init() {
	var err error
	timeout, err = time.ParseDuration(timeoutString)
	if err != nil {
		panic(err)
	}
80 81 82 83

	for _, s := range outputRoomEventTestData {
		clientEventTestData = append(clientEventTestData, clientEventJSONForOutputRoomEvent(s))
	}
84 85
}

86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
func createTestUser(database, username, token string) error {
	cmd := exec.Command(
		filepath.Join(filepath.Dir(os.Args[0]), "create-account"),
		"--database", database,
		"--username", username,
		"--token", token,
	)

	// Send stdout and stderr to our stderr so that we see error messages from
	// the create-account process
	cmd.Stdout = os.Stderr
	cmd.Stderr = os.Stderr
	return cmd.Run()
}

101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128
// clientEventJSONForOutputRoomEvent parses the given output room event and extracts the 'Event' JSON. It is
// trimmed to the client format and then canonicalised and returned as a string.
// Panics if there are any problems.
func clientEventJSONForOutputRoomEvent(outputRoomEvent string) string {
	var out api.OutputRoomEvent
	if err := json.Unmarshal([]byte(outputRoomEvent), &out); err != nil {
		panic("failed to unmarshal output room event: " + err.Error())
	}
	ev, err := gomatrixserverlib.NewEventFromTrustedJSON(out.Event, false)
	if err != nil {
		panic("failed to convert event field in output room event to Event: " + err.Error())
	}
	clientEvs := gomatrixserverlib.ToClientEvents([]gomatrixserverlib.Event{ev}, gomatrixserverlib.FormatSync)
	b, err := json.Marshal(clientEvs[0])
	if err != nil {
		panic("failed to marshal client event as json: " + err.Error())
	}
	jsonBytes, err := gomatrixserverlib.CanonicalJSON(b)
	if err != nil {
		panic("failed to turn event json into canonical json: " + err.Error())
	}
	return string(jsonBytes)
}

// startSyncServer creates the database and config file needed for the sync server to run and
// then starts the sync server. The Cmd being executed is returned. A channel is also returned,
// which will have any termination errors sent down it, followed immediately by the channel being closed.
func startSyncServer() (*exec.Cmd, chan error) {
129 130 131 132 133
	const configFilename = "sync-api-server-config-test.yaml"

	serverArgs := []string{
		"--config", configFilename,
		"--listen", syncserverAddr,
134 135
	}

136 137 138 139 140 141 142 143 144 145 146 147 148 149 150
	databases := []string{
		testDatabaseName,
	}

	cmd, cmdChan := test.StartServer(
		"sync-api",
		serverArgs,
		"",
		configFilename,
		syncServerConfigFileContents,
		postgresDatabase,
		postgresContainerName,
		databases,
	)

151 152 153 154 155 156 157 158 159 160
	if err := createTestUser(testDatabase, "alice", "@alice:localhost"); err != nil {
		panic(err)
	}
	if err := createTestUser(testDatabase, "bob", "@bob:localhost"); err != nil {
		panic(err)
	}
	if err := createTestUser(testDatabase, "charlie", "@charlie:localhost"); err != nil {
		panic(err)
	}

161
	return cmd, cmdChan
162 163
}

164 165
// prepareKafka creates the topics which will be written to by the tests.
func prepareKafka() {
166 167 168 169
	exe.DeleteTopic(inputTopic)
	if err := exe.CreateTopic(inputTopic); err != nil {
		panic(err)
	}
170
}
171

172 173
func testSyncServer(syncServerCmdChan chan error, userID, since, want string) {
	fmt.Printf("==TESTING== testSyncServer(%s,%s)\n", userID, since)
174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189
	sinceQuery := ""
	if since != "" {
		sinceQuery = "&since=" + since
	}
	req, err := http.NewRequest(
		"GET",
		"http://"+syncserverAddr+"/api/_matrix/client/r0/sync?timeout=100&access_token="+userID+sinceQuery,
		nil,
	)
	if err != nil {
		panic(err)
	}
	testReq := &test.Request{
		Req:              req,
		WantedStatusCode: 200,
		WantedBody:       test.CanonicalJSONInput([]string{want})[0],
190
	}
191
	testReq.Run("sync-api", timeout, syncServerCmdChan)
192 193
}

194 195 196 197 198
func writeToRoomServerLog(indexes ...int) {
	var roomEvents []string
	for _, i := range indexes {
		roomEvents = append(roomEvents, outputRoomEventTestData[i])
	}
199
	if err := exe.WriteToTopic(inputTopic, test.CanonicalJSONInput(roomEvents)); err != nil {
200 201 202 203
		panic(err)
	}
}

204 205 206 207
// Runs a battery of sync server tests against test data in testdata.go
// testdata.go has a list of OutputRoomEvents which will be fed into the kafka log which the sync server will consume.
// The tests will pause at various points in this list to conduct tests on the /sync responses before continuing.
// For ease of understanding, the curl commands used to create the OutputRoomEvents are listed along with each write to kafka.
208 209
func main() {
	fmt.Println("==TESTING==", os.Args[0])
210 211 212 213 214 215 216 217 218
	prepareKafka()
	cmd, syncServerCmdChan := startSyncServer()
	defer cmd.Process.Kill() // ensure server is dead, only cleaning up so don't care about errors this returns.

	// $ curl -XPOST -d '{}' "http://localhost:8009/_matrix/client/r0/createRoom?access_token=@alice:localhost"
	// $ curl -XPUT -d '{"msgtype":"m.text","body":"hello world"}' "http://localhost:8009/_matrix/client/r0/rooms/%21PjrbIMW2cIiaYF4t:localhost/send/m.room.message/1?access_token=@alice:localhost"
	// $ curl -XPUT -d '{"msgtype":"m.text","body":"hello world 2"}' "http://localhost:8009/_matrix/client/r0/rooms/%21PjrbIMW2cIiaYF4t:localhost/send/m.room.message/2?access_token=@alice:localhost"
	// $ curl -XPUT -d '{"msgtype":"m.text","body":"hello world 3"}' "http://localhost:8009/_matrix/client/r0/rooms/%21PjrbIMW2cIiaYF4t:localhost/send/m.room.message/3?access_token=@alice:localhost"
	// $ curl -XPUT -d '{"name":"Custom Room Name"}' "http://localhost:8009/_matrix/client/r0/rooms/%21PjrbIMW2cIiaYF4t:localhost/state/m.room.name?access_token=@alice:localhost"
219 220 221 222 223
	writeToRoomServerLog(
		i0StateRoomCreate, i1StateAliceJoin, i2StatePowerLevels, i3StateJoinRules, i4StateHistoryVisibility,
		i5AliceMsg, i6AliceMsg, i7AliceMsg, i8StateAliceRoomName,
	)

K
Kegsay 已提交
224
	// Make sure initial sync works TODO: prev_batch
225
	testSyncServer(syncServerCmdChan, "@alice:localhost", "", `{
226 227 228
		"account_data": {
			"events": []
		},
229
		"next_batch": "9",
230 231 232 233
		"presence": {
			"events": []
		},
		"rooms": {
234
			"invite": {},
235
			"join": {
236 237 238 239 240 241 242
				"!PjrbIMW2cIiaYF4t:localhost": {
					"account_data": {
						"events": []
					},
					"ephemeral": {
						"events": []
					},
243
					"state": {
244 245 246
						"events": []
					},
					"timeline": {
K
Kegsay 已提交
247
						"events": [`+
248 249 250 251 252 253 254 255 256
		clientEventTestData[i0StateRoomCreate]+","+
		clientEventTestData[i1StateAliceJoin]+","+
		clientEventTestData[i2StatePowerLevels]+","+
		clientEventTestData[i3StateJoinRules]+","+
		clientEventTestData[i4StateHistoryVisibility]+","+
		clientEventTestData[i5AliceMsg]+","+
		clientEventTestData[i6AliceMsg]+","+
		clientEventTestData[i7AliceMsg]+","+
		clientEventTestData[i8StateAliceRoomName]+`],
257
						"limited": true,
258 259 260 261
						"prev_batch": ""
					}
				}
			},
262 263 264
			"leave": {}
		}
	}`)
K
Kegsay 已提交
265
	// Make sure alice's rooms don't leak to bob
266 267 268 269 270 271 272 273 274
	testSyncServer(syncServerCmdChan, "@bob:localhost", "", `{
		"account_data": {
			"events": []
		},
		"next_batch": "9",
		"presence": {
			"events": []
		},
		"rooms": {
275
			"invite": {},
276
			"join": {},
277 278
			"leave": {}
		}
279
	}`)
K
Kegsay 已提交
280 281 282 283 284 285 286 287 288 289 290 291 292 293 294
	// Make sure polling with an up-to-date token returns nothing new
	testSyncServer(syncServerCmdChan, "@alice:localhost", "9", `{
		"account_data": {
			"events": []
		},
		"next_batch": "9",
		"presence": {
			"events": []
		},
		"rooms": {
			"invite": {},
			"join": {},
			"leave": {}
		}
	}`)
295 296

	// $ curl -XPUT -d '{"membership":"join"}' "http://localhost:8009/_matrix/client/r0/rooms/%21PjrbIMW2cIiaYF4t:localhost/state/m.room.member/@bob:localhost?access_token=@bob:localhost"
297
	writeToRoomServerLog(i9StateBobJoin)
K
Kegsay 已提交
298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323

	// Make sure alice sees it TODO: prev_batch
	testSyncServer(syncServerCmdChan, "@alice:localhost", "9", `{
		"account_data": {
			"events": []
		},
		"next_batch": "10",
		"presence": {
			"events": []
		},
		"rooms": {
			"invite": {},
			"join": {
				"!PjrbIMW2cIiaYF4t:localhost": {
					"account_data": {
						"events": []
					},
					"ephemeral": {
						"events": []
					},
					"state": {
						"events": []
					},
					"timeline": {
						"limited": false,
						"prev_batch": "",
324
						"events": [`+clientEventTestData[i9StateBobJoin]+`]
K
Kegsay 已提交
325 326 327 328 329 330 331
					}
				}
			},
			"leave": {}
		}
	}`)

332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352
	// Make sure bob sees the room AND all the current room state TODO: history visibility
	testSyncServer(syncServerCmdChan, "@bob:localhost", "9", `{
		"account_data": {
			"events": []
		},
		"next_batch": "10",
		"presence": {
			"events": []
		},
		"rooms": {
			"invite": {},
			"join": {
				"!PjrbIMW2cIiaYF4t:localhost": {
					"account_data": {
						"events": []
					},
					"ephemeral": {
						"events": []
					},
					"state": {
						"events": [`+
353 354 355 356 357 358
		clientEventTestData[i0StateRoomCreate]+","+
		clientEventTestData[i1StateAliceJoin]+","+
		clientEventTestData[i2StatePowerLevels]+","+
		clientEventTestData[i3StateJoinRules]+","+
		clientEventTestData[i4StateHistoryVisibility]+","+
		clientEventTestData[i8StateAliceRoomName]+`]
359 360 361 362 363
					},
					"timeline": {
						"limited": false,
						"prev_batch": "",
						"events": [`+
364
		clientEventTestData[i9StateBobJoin]+`]
365 366 367 368 369 370 371
					}
				}
			},
			"leave": {}
		}
	}`)

372
	// $ curl -XPUT -d '{"msgtype":"m.text","body":"hello alice"}' "http://localhost:8009/_matrix/client/r0/rooms/%21PjrbIMW2cIiaYF4t:localhost/send/m.room.message/1?access_token=@bob:localhost"
373 374
	writeToRoomServerLog(i10BobMsg)

K
Kegsay 已提交
375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400
	// Make sure alice can see everything around the join point for bob TODO: prev_batch
	testSyncServer(syncServerCmdChan, "@alice:localhost", "7", `{
		"account_data": {
			"events": []
		},
		"next_batch": "11",
		"presence": {
			"events": []
		},
		"rooms": {
			"invite": {},
			"join": {
				"!PjrbIMW2cIiaYF4t:localhost": {
					"account_data": {
						"events": []
					},
					"ephemeral": {
						"events": []
					},
					"state": {
						"events": []
					},
					"timeline": {
						"limited": false,
						"prev_batch": "",
						"events": [`+
401 402 403 404
		clientEventTestData[i7AliceMsg]+","+
		clientEventTestData[i8StateAliceRoomName]+","+
		clientEventTestData[i9StateBobJoin]+","+
		clientEventTestData[i10BobMsg]+`]
K
Kegsay 已提交
405 406 407 408 409 410 411
					}
				}
			},
			"leave": {}
		}
	}`)

412 413 414
	// $ curl -XPUT -d '{"name":"A Different Custom Room Name"}' "http://localhost:8009/_matrix/client/r0/rooms/%21PjrbIMW2cIiaYF4t:localhost/state/m.room.name?access_token=@alice:localhost"
	// $ curl -XPUT -d '{"msgtype":"m.text","body":"hello bob"}' "http://localhost:8009/_matrix/client/r0/rooms/%21PjrbIMW2cIiaYF4t:localhost/send/m.room.message/2?access_token=@alice:localhost"
	// $ curl -XPUT -d '{"membership":"invite"}' "http://localhost:8009/_matrix/client/r0/rooms/%21PjrbIMW2cIiaYF4t:localhost/state/m.room.member/@charlie:localhost?access_token=@bob:localhost"
415
	writeToRoomServerLog(i11StateAliceRoomName, i12AliceMsg, i13StateBobInviteCharlie)
K
Kegsay 已提交
416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441

	// Make sure charlie sees the invite both with and without a ?since= token
	// TODO: Invite state should include the invite event and the room name.
	charlieInviteData := `{
		"account_data": {
			"events": []
		},
		"next_batch": "14",
		"presence": {
			"events": []
		},
		"rooms": {
			"invite": {
				"!PjrbIMW2cIiaYF4t:localhost": {
					"invite_state": {
						"events": []
					}
				}
			},
			"join": {},
			"leave": {}
		}
	}`
	testSyncServer(syncServerCmdChan, "@charlie:localhost", "7", charlieInviteData)
	testSyncServer(syncServerCmdChan, "@charlie:localhost", "", charlieInviteData)

442 443 444
	// $ curl -XPUT -d '{"membership":"join"}' "http://localhost:8009/_matrix/client/r0/rooms/%21PjrbIMW2cIiaYF4t:localhost/state/m.room.member/@charlie:localhost?access_token=@charlie:localhost"
	// $ curl -XPUT -d '{"msgtype":"m.text","body":"not charlie..."}' "http://localhost:8009/_matrix/client/r0/rooms/%21PjrbIMW2cIiaYF4t:localhost/send/m.room.message/3?access_token=@alice:localhost"
	// $ curl -XPUT -d '{"membership":"leave"}' "http://localhost:8009/_matrix/client/r0/rooms/%21PjrbIMW2cIiaYF4t:localhost/state/m.room.member/@charlie:localhost?access_token=@alice:localhost"
445 446
	// $ curl -XPUT -d '{"msgtype":"m.text","body":"why did you kick charlie"}' "http://localhost:8009/_matrix/client/r0/rooms/%21PjrbIMW2cIiaYF4t:localhost/send/m.room.message/3?access_token=@bob:localhost"
	writeToRoomServerLog(i14StateCharlieJoin, i15AliceMsg, i16StateAliceKickCharlie, i17BobMsg)
447 448 449 450 451 452

	// Check transitions to leave work
	testSyncServer(syncServerCmdChan, "@charlie:localhost", "15", `{
		"account_data": {
			"events": []
		},
453
		"next_batch": "18",
454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484
		"presence": {
			"events": []
		},
		"rooms": {
			"invite": {},
			"join": {},
			"leave": {
				"!PjrbIMW2cIiaYF4t:localhost": {
					"state": {
						"events": []
					},
					"timeline": {
						"limited": false,
						"prev_batch": "",
						"events": [`+
		clientEventTestData[i15AliceMsg]+","+
		clientEventTestData[i16StateAliceKickCharlie]+`]
					}
				}
			}
		}
	}`)

	// Test joining and leaving the same room in a single /sync request puts the room in the 'leave' section.
	// TODO: Use an earlier since value to assert that the /sync response doesn't leak messages
	//       from before charlie was joined to the room. Currently it does leak because RecentEvents doesn't
	//       take membership into account.
	testSyncServer(syncServerCmdChan, "@charlie:localhost", "14", `{
		"account_data": {
			"events": []
		},
485
		"next_batch": "18",
486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509
		"presence": {
			"events": []
		},
		"rooms": {
			"invite": {},
			"join": {},
			"leave": {
				"!PjrbIMW2cIiaYF4t:localhost": {
					"state": {
						"events": []
					},
					"timeline": {
						"limited": false,
						"prev_batch": "",
						"events": [`+
		clientEventTestData[i14StateCharlieJoin]+","+
		clientEventTestData[i15AliceMsg]+","+
		clientEventTestData[i16StateAliceKickCharlie]+`]
					}
				}
			}
		}
	}`)

510
	// $ curl -XPUT -d '{"name":"No Charlies"}' "http://localhost:8009/_matrix/client/r0/rooms/%21PjrbIMW2cIiaYF4t:localhost/state/m.room.name?access_token=@alice:localhost"
511
	writeToRoomServerLog(i18StateAliceRoomName)
512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528

	// Check that users don't see state changes in rooms after they have left
	testSyncServer(syncServerCmdChan, "@charlie:localhost", "17", `{
		"account_data": {
			"events": []
		},
		"next_batch": "19",
		"presence": {
			"events": []
		},
		"rooms": {
			"invite": {},
			"join": {},
			"leave": {}
		}
	}`)

529 530 531 532 533 534 535 536 537
	// $ curl -XPUT -d '{"msgtype":"m.text","body":"whatever"}' "http://localhost:8009/_matrix/client/r0/rooms/%21PjrbIMW2cIiaYF4t:localhost/send/m.room.message/3?access_token=@bob:localhost"
	// $ curl -XPUT -d '{"membership":"leave"}' "http://localhost:8009/_matrix/client/r0/rooms/%21PjrbIMW2cIiaYF4t:localhost/state/m.room.member/@bob:localhost?access_token=@bob:localhost"
	// $ curl -XPUT -d '{"msgtype":"m.text","body":"im alone now"}' "http://localhost:8009/_matrix/client/r0/rooms/%21PjrbIMW2cIiaYF4t:localhost/send/m.room.message/3?access_token=@alice:localhost"
	// $ curl -XPUT -d '{"membership":"invite"}' "http://localhost:8009/_matrix/client/r0/rooms/%21PjrbIMW2cIiaYF4t:localhost/state/m.room.member/@bob:localhost?access_token=@alice:localhost"
	// $ curl -XPUT -d '{"membership":"leave"}' "http://localhost:8009/_matrix/client/r0/rooms/%21PjrbIMW2cIiaYF4t:localhost/state/m.room.member/@bob:localhost?access_token=@bob:localhost"
	// $ curl -XPUT -d '{"msgtype":"m.text","body":"so alone"}' "http://localhost:8009/_matrix/client/r0/rooms/%21PjrbIMW2cIiaYF4t:localhost/send/m.room.message/3?access_token=@alice:localhost"
	// $ curl -XPUT -d '{"name":"Everyone welcome"}' "http://localhost:8009/_matrix/client/r0/rooms/%21PjrbIMW2cIiaYF4t:localhost/state/m.room.name?access_token=@alice:localhost"
	// $ curl -XPUT -d '{"membership":"join"}' "http://localhost:8009/_matrix/client/r0/rooms/%21PjrbIMW2cIiaYF4t:localhost/state/m.room.member/@charlie:localhost?access_token=@charlie:localhost"
	// $ curl -XPUT -d '{"msgtype":"m.text","body":"hiiiii"}' "http://localhost:8009/_matrix/client/r0/rooms/%21PjrbIMW2cIiaYF4t:localhost/send/m.room.message/3?access_token=@charlie:localhost"
538
}