Phase 4: sync
CI / Test (ubuntu-latest) (push) Canceled after 0s
CI / Test (windows-latest) (push) Canceled after 0s
CI / Storage tests on PostgreSQL (push) Canceled after 0s
CI / Complement (federation off) (push) Canceled after 0s
CI / golangci-lint (push) Canceled after 0s
CI / Smoke test the binary (push) Canceled after 0s

Implements PLAN.md Phase 4: the read model. /sync, /messages and /context,
the filters that narrow them, and the streams a response carries that are
not room events — typing, receipts, presence and to-device messages. With
this a client can be used against Warp, which is milestone M1.

The one architectural choice is that the syncapi has no copy of the rooms:
it reads them through the roomserver. Dendrite gives its syncapi its own
tables and feeds them from the output stream, which is right for a design
where the two can be separate processes, and Dendrite's could be. Warp is
one process by decision, and there the copy buys nothing and costs the
hardest class of bug a homeserver has — a read model that disagrees with
the room, where a client is shown a message that was rejected and the only
way to find out is to compare two tables. So the roomserver grew a read
model (stream.go, roomsync.go, visibility.go) rather than exporting its
store: reading an event means parsing it under its room's version, and a
second copy of the version registry, the parser and the client projection
would be a second place for them to disagree.

syncapi: stream tokens naming a position in each of five independent
streams, so a client that has seen receipt 7 but only event 4 can say so in
one opaque string. A token with fewer positions than this build writes is
accepted and the rest read as zero, which is what lets a token stored
before a stream existed go on working. The PDU position comes from
MAX(stream_ordering) and not from the counter row the other four use: the
counter is advanced inside the writing transaction, so a token taken from
it would name a position whose event no reader can see yet, and the event
would be skipped for good once that transaction committed.

Long polling goes through a notifier that wakes by room and by user rather
than globally — an event wakes the listeners of its room, a membership
event also wakes the user it names, so an invite reaches a client that is
not in the room yet. A wake-up is only ever a hint: the listener re-reads
the streams and decides for itself what changed, which is what makes it
safe for the notifier to hold no state about what each client has seen. The
listener registers before the read, so an event landing in between leaves
the channel signalled and the sync reads again rather than blocking on a
change it just missed. EventPersisted must not block, because it is called
with the room's write lock still held.

"Something happened" is not "a token moved". A stream can move without this
user being concerned by it, and returning on every such move would turn a
long poll back into a busy loop. The same trap caught presence twice over:
a client says it is still online by syncing, so ?set_presence= makes every
sync a presence write, and a stream that moved each time would wake every
peer, which would sync, which would move it again. SetPresence therefore
reports whether anything a peer would notice actually changed, and a write
that only refreshes the last-active timestamp leaves the stream alone.

Timeline windows are named by their two ends and a direction, Low exclusive
and High inclusive in both directions, rather than by "from" and "to" as
the wire format spells them. Each of those would otherwise be the low bound
in one direction and the high bound in the other, which is exactly the
off-by-one every pagination bug is made of; the handlers translate once and
nothing below them thinks about it again. A sync's timeline is read
backwards and reported forwards, because a client wants the newest events
of the window it missed — a forward read with a limit hands it the oldest
and then calls the rest a gap.

visibility: history visibility is now a span rather than a yes or no, which
is what Phase 3 deferred here. A user who has left a room is served the
room as it was when they left — their state reads, their members and their
timeline — instead of being refused, and is bounded above at their own
membership event so a kicked client cannot go on streaming. Their span is
found from their own member events, so a user who joined, left and rejoined
sees their latest span. ?at= on /members is honoured for the same reason.
What is left is that the span is computed from the room's current
history_visibility where the spec judges each event by the one in force
when it was sent; that is a state read per event and belongs with open
question 1.

Typing is held in memory and nowhere else: notifications expire in seconds,
are worthless across a restart, and arrive one per keystroke-burst per
room, so persisting them would be the busiest table in the database holding
the least valuable data in it. Receipts only ever advance, compared on the
position of the event acknowledged rather than on arrival, because two of a
user's clients read at different speeds and the slower one must not drag
the marker backwards. To-device queues are per device and drained by the
next sync rather than by the one that delivered them, so a client that
crashes in between gets the batch again — the right way round, since a lost
key share leaves a message permanently undecryptable and a duplicate is
ignored. A wildcard addressee is expanded when sent, not stored, because
"every device" means the ones that existed then.

Presence is off by default, which answers PLAN.md open question 3. It is
the noisiest thing in Matrix and the one genuinely fan-out notification
here; a private homeserver gains little from it. With it off the endpoints
refuse rather than disappearing, because a client that gets a 404 from
/presence concludes the server is too old to have it and stops asking.

storage: one migration per driver adding the receipt, to-device, presence
and filter tables with a counter row each, and a stream position on the
existing account data table rather than a parallel one — there is exactly
one current value per (user, room, type), and a second table would be a
second thing to keep in step. Account data is reported in an event list but
is not an event, so it gets its own response type: a room event with an
empty sender and no timestamp would make a client decide what that meant.

Deliberately missing, each named in docs/sync.md: notification counts (they
need push rules, Phase 8), device lists (the keyserver, Phase 7), anything
remote (Phase 5), threads (Phase 10). device_lists is sent as two empty
lists because a client reads a missing one as malformed; the notification
counts are left out entirely, because a zero there is a claim and an absent
field is not.

Tested through HTTP rather than against the builder, because what is worth
pinning down is the response a client sees — which section a room lands in,
whether a token handed back can be handed in again, whether paging
terminates and loses nothing. The storage tests run against both SQL
drivers; the notifier has its own tests for the concurrent case. A live
server was driven end to end, which is what caught the two bugs the unit
tests had missed: a backwards /messages page must be in reverse
chronological order, and `start` must name where the page began rather than
position zero when ?from= was omitted.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
tajniak81andClaude Opus 5 committed 2026-10-16 11:55:27 +02:00
1 parent c96f88e994
commit d187ad0d17
60 files changed
+10196 -264

No files matched your search

+55 -2
View File
@@ -23,6 +23,7 @@ import (
"github.com/dariuszjaniak/warp/server/internal/ratelimit"
"github.com/dariuszjaniak/warp/server/internal/roomserver"
"github.com/dariuszjaniak/warp/server/internal/settings"
"github.com/dariuszjaniak/warp/server/internal/syncapi"
"github.com/dariuszjaniak/warp/server/internal/userapi"
)
@@ -32,6 +33,7 @@ type ClientAPI struct {
clientBaseURL string
users *userapi.API
rooms *roomserver.API
sync *syncapi.API
settings *settings.Service
federation *federation.Gate
registration config.Registration
@@ -48,6 +50,12 @@ type ClientAPI struct {
limitRegister *ratelimit.Limiter
limitRoomCreate *ratelimit.Limiter
limitJoin *ratelimit.Limiter
// limitSync is deliberately generous. A client is in /sync all the
// time, and a long poll that is refused leaves it reconnecting in a
// loop — the one place where rate limiting makes the load worse rather
// than better.
limitSync *ratelimit.Limiter
}
// Options configure the component.
@@ -70,6 +78,12 @@ type Options struct {
// createRoom it cannot honour.
Rooms *roomserver.API
// Sync is the syncapi component. Like the roomserver it is optional,
// and for the same reason: without it /sync, /messages, /context and
// the ephemeral endpoints answer M_UNRECOGNIZED rather than
// pretending there is a stream to read.
Sync *syncapi.API
// Settings is the runtime-settings service; the registration switch is
// read from it on every registration attempt.
Settings *settings.Service
@@ -118,6 +132,7 @@ func New(opts Options) (*ClientAPI, error) {
clientBaseURL: opts.ClientBaseURL,
users: opts.Users,
rooms: opts.Rooms,
sync: opts.Sync,
settings: opts.Settings,
federation: opts.Federation,
registration: opts.Registration,
@@ -137,10 +152,12 @@ func New(opts Options) (*ClientAPI, error) {
// reads.
c.limitRoomCreate = ratelimit.New(bucket(opts.RateLimit.RoomCreate))
c.limitJoin = ratelimit.New(bucket(opts.RateLimit.Join))
c.limitSync = ratelimit.New(bucket(opts.RateLimit.Sync))
} else {
c.limitDefault, c.limitLogin, c.limitRegister =
ratelimit.Disabled(), ratelimit.Disabled(), ratelimit.Disabled()
c.limitRoomCreate, c.limitJoin = ratelimit.Disabled(), ratelimit.Disabled()
c.limitSync = ratelimit.Disabled()
}
return c, nil
}
@@ -204,9 +221,45 @@ func (c *ClientAPI) RegisterRoutes(r *httputil.Router) {
c.authed(r, "PUT "+v3+"/user/{userID}/rooms/{roomID}/account_data/{dataType}",
c.limitDefault, c.handlePutRoomAccountData)
c.authed(r, "GET "+v3+"/sync", c.limitDefault, c.handleSync)
c.registerRoomRoutes(r)
c.registerSyncRoutes(r)
}
// registerSyncRoutes adds the endpoints the syncapi serves, if there is
// one.
//
// Like the room routes they are left unregistered rather than stubbed in a
// build without the component: a client that gets M_UNRECOGNIZED from
// /sync knows the server does not have it, where an empty success would
// have it believe nothing was happening.
func (c *ClientAPI) registerSyncRoutes(r *httputil.Router) {
if c.sync == nil {
return
}
c.authed(r, "GET "+v3+"/sync", c.limitSync, c.handleSync)
c.authed(r, "GET "+v3+"/rooms/{roomID}/messages", c.limitDefault, c.handleMessages)
c.authed(r, "GET "+v3+"/rooms/{roomID}/context/{eventID}", c.limitDefault, c.handleContext)
// Filters.
c.authed(r, "POST "+v3+"/user/{userID}/filter", c.limitDefault, c.handlePostFilter)
c.authed(r, "GET "+v3+"/user/{userID}/filter/{filterID}", c.limitDefault, c.handleGetFilter)
// The ephemeral streams. Typing goes in the sync limiter's class
// rather than the default one: a client sends one per keystroke-burst,
// and it is the chattiest write in the API.
c.authed(r, "PUT "+v3+"/rooms/{roomID}/typing/{userID}", c.limitSync, c.handlePutTyping)
c.authed(r, "POST "+v3+"/rooms/{roomID}/receipt/{receiptType}/{eventID}",
c.limitSync, c.handlePostReceipt)
c.authed(r, "POST "+v3+"/rooms/{roomID}/read_markers", c.limitDefault, c.handlePostReadMarkers)
// To-device messaging. A client encrypting for a busy room sends one
// of these per device, so it shares the sync budget too.
c.authed(r, "PUT "+v3+"/sendToDevice/{eventType}/{txnID}", c.limitSync, c.handleSendToDevice)
// Presence.
c.authed(r, "GET "+v3+"/presence/{userID}/status", c.limitDefault, c.handleGetPresence)
c.authed(r, "PUT "+v3+"/presence/{userID}/status", c.limitSync, c.handlePutPresence)
}
// registerRoomRoutes adds the room endpoints, if there is a roomserver.
@@ -19,6 +19,7 @@ import (
"github.com/dariuszjaniak/warp/server/internal/settings"
"github.com/dariuszjaniak/warp/server/internal/storage"
_ "github.com/dariuszjaniak/warp/server/internal/storage/drivers"
"github.com/dariuszjaniak/warp/server/internal/syncapi"
"github.com/dariuszjaniak/warp/server/internal/userapi"
)
@@ -34,8 +35,10 @@ type testServer struct {
handler http.Handler
users *userapi.API
rooms *roomserver.API
syncAPI *syncapi.API
settings *settings.Service
fedGate *federation.Gate
db storage.Database
}
// newTestServer builds a server. tweak adjusts the options before the
@@ -84,22 +87,45 @@ func newTestServer(t *testing.T, tweak func(*clientapi.Options)) *testServer {
if err != nil {
t.Fatalf("signing.Generate: %v", err)
}
// The notifier is the seam between the two: the roomserver's emit
// stage and the syncapi's wake-up are the same object, exactly as in
// a real server.
notifier := syncapi.NewNotifier()
rooms, err := roomserver.New(roomserver.Options{
ServerName: testServerName,
Store: db.Rooms(),
Profiles: users,
SigningKey: key,
FederationEnabled: settingsService.FederationEnabled,
Notifier: notifier,
Logger: slog.New(slog.DiscardHandler),
})
if err != nil {
t.Fatalf("roomserver.New: %v", err)
}
// Presence is on in tests and off in a default config: the tests are
// the only thing that exercises it, and a switch nothing turns on is
// a switch nothing tests.
sync, err := syncapi.New(syncapi.Options{
ServerName: testServerName,
Rooms: rooms,
Accounts: users,
Store: db.Sync(),
Notifier: notifier,
PresenceEnabled: true,
Logger: slog.New(slog.DiscardHandler),
})
if err != nil {
t.Fatalf("syncapi.New: %v", err)
}
t.Cleanup(sync.Close)
opts := clientapi.Options{
ServerName: testServerName,
Users: users,
Rooms: rooms,
Sync: sync,
Settings: settingsService,
Federation: gate,
Logger: slog.New(slog.DiscardHandler),
@@ -120,8 +146,10 @@ func newTestServer(t *testing.T, tweak func(*clientapi.Options)) *testServer {
handler: router,
users: users,
rooms: rooms,
syncAPI: sync,
settings: settingsService,
fedGate: gate,
db: db,
}
}
+269
View File
@@ -0,0 +1,269 @@
package clientapi
import (
"encoding/json"
"net/http"
"time"
"github.com/dariuszjaniak/warp/server/internal/httputil"
"github.com/dariuszjaniak/warp/server/internal/syncapi"
"github.com/dariuszjaniak/warp/server/internal/userapi"
)
// The endpoints behind the streams that are not room events: typing,
// receipts, read markers, to-device messages and presence.
//
// They are all writes, and all of them are writes a client makes constantly
// — a typing notification per keystroke-burst, a receipt per message read.
// None of them creates an event, which is why none of them goes through the
// roomserver.
// typingRequest is the PUT /rooms/{roomID}/typing/{userID} body.
type typingRequest struct {
Typing bool `json:"typing"`
// Timeout is in milliseconds, and is only meaningful when Typing is
// true.
Timeout int64 `json:"timeout"`
}
// handlePutTyping implements
// PUT /_matrix/client/v3/rooms/{roomID}/typing/{userID}.
func (c *ClientAPI) handlePutTyping(w http.ResponseWriter, r *http.Request, auth userapi.Authenticated) error {
roomID, err := pathRoomID(r)
if err != nil {
return err
}
if err := requireOwnUserID(auth, r.PathValue("userID")); err != nil {
return err
}
var req typingRequest
if err := httputil.DecodeJSON(w, r, &req); err != nil {
return err
}
if req.Timeout < 0 {
return httputil.InvalidParam("timeout must not be negative")
}
if err := c.sync.SetTyping(r.Context(), syncapi.TypingRequest{
RoomID: roomID,
User: auth.UserID,
Typing: req.Typing,
Timeout: time.Duration(req.Timeout) * time.Millisecond,
}); err != nil {
return syncError(err)
}
httputil.WriteJSON(w, http.StatusOK, struct{}{})
return nil
}
// receiptRequest is the POST /rooms/{roomID}/receipt/{receiptType}/{eventID}
// body. Every field is optional; the only one defined is the thread.
type receiptRequest struct {
ThreadID string `json:"thread_id"`
}
// handlePostReceipt implements
// POST /_matrix/client/v3/rooms/{roomID}/receipt/{receiptType}/{eventID}.
func (c *ClientAPI) handlePostReceipt(w http.ResponseWriter, r *http.Request, auth userapi.Authenticated) error {
roomID, err := pathRoomID(r)
if err != nil {
return err
}
receiptType := r.PathValue("receiptType")
if receiptType == "" {
return httputil.MissingParam("A receipt type is required")
}
eventID := r.PathValue("eventID")
if eventID == "" {
return httputil.MissingParam("An event ID is required")
}
// The body is optional: a client marking a room read sends none.
var req receiptRequest
if _, err := httputil.DecodeOptionalJSON(w, r, &req); err != nil {
return err
}
if err := c.sync.SetReceipt(r.Context(), syncapi.ReceiptRequest{
RoomID: roomID,
User: auth.UserID,
ReceiptType: receiptType,
EventID: eventID,
ThreadID: req.ThreadID,
}); err != nil {
return syncError(err)
}
httputil.WriteJSON(w, http.StatusOK, struct{}{})
return nil
}
// readMarkersRequest is the POST /rooms/{roomID}/read_markers body.
type readMarkersRequest struct {
FullyRead string `json:"m.fully_read"`
Read string `json:"m.read"`
ReadPrivate string `json:"m.read.private"`
}
// handlePostReadMarkers implements
// POST /_matrix/client/v3/rooms/{roomID}/read_markers.
func (c *ClientAPI) handlePostReadMarkers(w http.ResponseWriter, r *http.Request, auth userapi.Authenticated) error {
roomID, err := pathRoomID(r)
if err != nil {
return err
}
var req readMarkersRequest
if err := httputil.DecodeJSON(w, r, &req); err != nil {
return err
}
if req.FullyRead == "" && req.Read == "" && req.ReadPrivate == "" {
return httputil.MissingParam(
"At least one of m.fully_read, m.read or m.read.private is required")
}
if err := c.sync.SetReadMarkers(r.Context(), syncapi.ReadMarkersRequest{
RoomID: roomID,
User: auth.UserID,
FullyRead: req.FullyRead,
Read: req.Read,
ReadPrivate: req.ReadPrivate,
}); err != nil {
return syncError(err)
}
httputil.WriteJSON(w, http.StatusOK, struct{}{})
return nil
}
// sendToDeviceRequest is the PUT /sendToDevice/{eventType}/{txnID} body.
type sendToDeviceRequest struct {
Messages map[string]map[string]json.RawMessage `json:"messages"`
}
// handleSendToDevice implements
// PUT /_matrix/client/v3/sendToDevice/{eventType}/{txnID}.
//
// The transaction ID is accepted and not used. Its purpose is idempotency,
// and a to-device message is already idempotent in the way that matters: a
// duplicate is a second copy of a key share, which the receiving client
// discards. Recording the transaction would mean a table whose only reader
// would be a retry that costs nothing anyway.
func (c *ClientAPI) handleSendToDevice(w http.ResponseWriter, r *http.Request, auth userapi.Authenticated) error {
eventType := r.PathValue("eventType")
if eventType == "" {
return httputil.MissingParam("An event type is required")
}
if r.PathValue("txnID") == "" {
return httputil.MissingParam("A transaction ID is required")
}
var req sendToDeviceRequest
if err := httputil.DecodeJSON(w, r, &req); err != nil {
return err
}
if err := c.sync.SendToDevice(r.Context(), syncapi.SendToDeviceRequest{
Sender: auth.UserID,
EventType: eventType,
Messages: req.Messages,
}); err != nil {
return syncError(err)
}
httputil.WriteJSON(w, http.StatusOK, struct{}{})
return nil
}
// presenceRequest is the PUT /presence/{userID}/status body.
type presenceRequest struct {
Presence string `json:"presence"`
// StatusMsg is a pointer so that a request which does not mention it
// can be told from one that clears it.
StatusMsg *string `json:"status_msg"`
}
// presenceResponse is what GET /presence/{userID}/status returns.
type presenceResponse struct {
Presence string `json:"presence"`
StatusMsg string `json:"status_msg,omitempty"`
// LastActiveAgo is milliseconds since the user was last seen, left out
// for a user nothing is known about.
LastActiveAgo *int64 `json:"last_active_ago,omitempty"`
// CurrentlyActive is only meaningful while the user is online.
CurrentlyActive bool `json:"currently_active,omitempty"`
}
// handlePutPresence implements
// PUT /_matrix/client/v3/presence/{userID}/status.
func (c *ClientAPI) handlePutPresence(w http.ResponseWriter, r *http.Request, auth userapi.Authenticated) error {
if err := requireOwnUserID(auth, r.PathValue("userID")); err != nil {
return err
}
var req presenceRequest
if err := httputil.DecodeJSON(w, r, &req); err != nil {
return err
}
if req.Presence == "" {
return httputil.MissingParam("A presence state is required")
}
if err := c.sync.SetPresence(r.Context(), syncapi.PresenceRequest{
User: auth.UserID,
Presence: req.Presence,
StatusMsg: req.StatusMsg,
}); err != nil {
return syncError(err)
}
httputil.WriteJSON(w, http.StatusOK, struct{}{})
return nil
}
// handleGetPresence implements
// GET /_matrix/client/v3/presence/{userID}/status.
//
// Anybody may ask about anybody: the spec has no visibility rule on
// presence beyond the server choosing who to publish changes to, and a
// client showing a room's member list asks about every member.
func (c *ClientAPI) handleGetPresence(w http.ResponseWriter, r *http.Request, _ userapi.Authenticated) error {
userID := r.PathValue("userID")
if userID == "" {
return httputil.MissingParam("A user ID is required")
}
state, err := c.sync.Presence(r.Context(), userID)
if err != nil {
return syncError(err)
}
resp := presenceResponse{
Presence: state.Presence,
StatusMsg: state.StatusMsg,
CurrentlyActive: state.Presence == syncapi.PresenceOnline,
}
if state.LastActiveMS > 0 {
ago := max(c.now().UnixMilli()-state.LastActiveMS, 0)
resp.LastActiveAgo = &ago
}
httputil.WriteJSON(w, http.StatusOK, resp)
return nil
}
// requireOwnUserID insists that the user ID in a path is the caller's.
//
// Typing and presence are claims about the caller, not data belonging to
// them, so unlike a profile an admin may not set them for somebody else:
// there is no administrative reason to say that another user is typing.
func requireOwnUserID(auth userapi.Authenticated, pathUserID string) error {
if pathUserID == "" {
return httputil.MissingParam("A user ID is required")
}
if pathUserID != auth.UserID {
return httputil.Forbidden("Cannot act on behalf of another user")
}
return nil
}
+362
View File
@@ -0,0 +1,362 @@
package clientapi_test
import (
"fmt"
"net/http"
"net/url"
"testing"
)
// The streams that are not room events: typing, receipts, read markers,
// to-device messages and presence.
// ephemeralEvent finds a room's ephemeral EDU of a type in a sync result.
func ephemeralEvent(result syncResult, roomID, eventType string) (syncEvent, bool) {
for _, e := range result.Rooms.Join[roomID].Ephemeral.Events {
if e.Type == eventType {
return e, true
}
}
return syncEvent{}, false
}
func TestTypingReachesTheOtherMembers(t *testing.T) {
ts := newTestServer(t, nil)
alice := ts.register("alice", "correct-horse-battery-staple")
bob := ts.register("bob", "hunter2-hunter2-hunter2")
roomID := ts.createRoom(alice, map[string]any{"preset": "public_chat"})
expectStatus(t, ts.post("/_matrix/client/v3/rooms/"+url.PathEscape(roomID)+"/join",
bob.AccessToken, map[string]any{}), http.StatusOK)
since := ts.sync(bob, "").NextBatch
expectStatus(t, ts.put(fmt.Sprintf("/_matrix/client/v3/rooms/%s/typing/%s",
url.PathEscape(roomID), url.PathEscape(alice.UserID)),
alice.AccessToken, map[string]any{"typing": true, "timeout": 30000}), http.StatusOK)
result := ts.sync(bob, since)
typing, ok := ephemeralEvent(result, roomID, "m.typing")
if !ok {
t.Fatalf("no m.typing in the ephemeral stream: %+v", result.Rooms.Join[roomID].Ephemeral)
}
users, _ := typing.Content["user_ids"].([]any)
if len(users) != 1 || users[0] != alice.UserID {
t.Errorf("user_ids = %v, want [%s]", users, alice.UserID)
}
// Stopping is reported as the list without them, not as nothing: a
// client replaces what it had.
expectStatus(t, ts.put(fmt.Sprintf("/_matrix/client/v3/rooms/%s/typing/%s",
url.PathEscape(roomID), url.PathEscape(alice.UserID)),
alice.AccessToken, map[string]any{"typing": false}), http.StatusOK)
stopped := ts.sync(bob, result.NextBatch)
if _, ok := ephemeralEvent(stopped, roomID, "m.typing"); ok {
t.Error("m.typing was still reported after the notification was withdrawn")
}
}
func TestTypingIsOnlyAboutTheCaller(t *testing.T) {
ts := newTestServer(t, nil)
alice := ts.register("alice", "correct-horse-battery-staple")
bob := ts.register("bob", "hunter2-hunter2-hunter2")
roomID := ts.createRoom(alice, map[string]any{"preset": "public_chat"})
rec := ts.put(fmt.Sprintf("/_matrix/client/v3/rooms/%s/typing/%s",
url.PathEscape(roomID), url.PathEscape(bob.UserID)),
alice.AccessToken, map[string]any{"typing": true})
expectError(t, rec, http.StatusForbidden, "M_FORBIDDEN")
}
func TestTypingRequiresMembership(t *testing.T) {
ts := newTestServer(t, nil)
alice := ts.register("alice", "correct-horse-battery-staple")
bob := ts.register("bob", "hunter2-hunter2-hunter2")
roomID := ts.createRoom(alice, map[string]any{"preset": "public_chat"})
rec := ts.put(fmt.Sprintf("/_matrix/client/v3/rooms/%s/typing/%s",
url.PathEscape(roomID), url.PathEscape(bob.UserID)),
bob.AccessToken, map[string]any{"typing": true})
expectError(t, rec, http.StatusForbidden, "M_FORBIDDEN")
}
func TestReceiptReachesTheRoom(t *testing.T) {
ts := newTestServer(t, nil)
alice := ts.register("alice", "correct-horse-battery-staple")
bob := ts.register("bob", "hunter2-hunter2-hunter2")
roomID := ts.createRoom(alice, map[string]any{"preset": "public_chat"})
expectStatus(t, ts.post("/_matrix/client/v3/rooms/"+url.PathEscape(roomID)+"/join",
bob.AccessToken, map[string]any{}), http.StatusOK)
eventID := ts.sendMessage(alice, roomID, "read me")
since := ts.sync(alice, "").NextBatch
expectStatus(t, ts.post(fmt.Sprintf("/_matrix/client/v3/rooms/%s/receipt/m.read/%s",
url.PathEscape(roomID), url.PathEscape(eventID)),
bob.AccessToken, map[string]any{}), http.StatusOK)
result := ts.sync(alice, since)
receipts, ok := ephemeralEvent(result, roomID, "m.receipt")
if !ok {
t.Fatalf("no m.receipt in the ephemeral stream: %+v", result.Rooms.Join[roomID].Ephemeral)
}
// The shape is event ID -> receipt type -> user ID -> data.
byType, _ := receipts.Content[eventID].(map[string]any)
byUser, _ := byType["m.read"].(map[string]any)
if _, found := byUser[bob.UserID]; !found {
t.Errorf("m.receipt does not name %s: %+v", bob.UserID, receipts.Content)
}
}
func TestPrivateReceiptStaysWithItsSender(t *testing.T) {
ts := newTestServer(t, nil)
alice := ts.register("alice", "correct-horse-battery-staple")
bob := ts.register("bob", "hunter2-hunter2-hunter2")
roomID := ts.createRoom(alice, map[string]any{"preset": "public_chat"})
expectStatus(t, ts.post("/_matrix/client/v3/rooms/"+url.PathEscape(roomID)+"/join",
bob.AccessToken, map[string]any{}), http.StatusOK)
eventID := ts.sendMessage(alice, roomID, "read me privately")
aliceSince := ts.sync(alice, "").NextBatch
bobSince := ts.sync(bob, "").NextBatch
expectStatus(t, ts.post(fmt.Sprintf("/_matrix/client/v3/rooms/%s/receipt/m.read.private/%s",
url.PathEscape(roomID), url.PathEscape(eventID)),
bob.AccessToken, map[string]any{}), http.StatusOK)
// Bob sees his own.
own := ts.sync(bob, bobSince)
if _, ok := ephemeralEvent(own, roomID, "m.receipt"); !ok {
t.Error("a private receipt must be reported back to its sender")
}
// Alice does not.
theirs := ts.sync(alice, aliceSince)
if e, ok := ephemeralEvent(theirs, roomID, "m.receipt"); ok {
t.Errorf("a private receipt leaked to another member: %+v", e.Content)
}
}
func TestReceiptForAnUnknownEventIsNotFound(t *testing.T) {
ts := newTestServer(t, nil)
alice := ts.register("alice", "correct-horse-battery-staple")
roomID := ts.createRoom(alice, nil)
rec := ts.post("/_matrix/client/v3/rooms/"+url.PathEscape(roomID)+"/receipt/m.read/$nope",
alice.AccessToken, map[string]any{})
expectError(t, rec, http.StatusNotFound, "M_NOT_FOUND")
}
func TestReceiptOfAnUnknownTypeIsRefused(t *testing.T) {
ts := newTestServer(t, nil)
alice := ts.register("alice", "correct-horse-battery-staple")
roomID := ts.createRoom(alice, nil)
eventID := ts.sendMessage(alice, roomID, "hello")
rec := ts.post(fmt.Sprintf("/_matrix/client/v3/rooms/%s/receipt/m.invented/%s",
url.PathEscape(roomID), url.PathEscape(eventID)), alice.AccessToken, map[string]any{})
expectError(t, rec, http.StatusBadRequest, "M_INVALID_PARAM")
}
func TestReadMarkersSetTheFullyReadAccountData(t *testing.T) {
ts := newTestServer(t, nil)
alice := ts.register("alice", "correct-horse-battery-staple")
roomID := ts.createRoom(alice, nil)
eventID := ts.sendMessage(alice, roomID, "up to here")
since := ts.sync(alice, "").NextBatch
expectStatus(t, ts.post("/_matrix/client/v3/rooms/"+url.PathEscape(roomID)+"/read_markers",
alice.AccessToken, map[string]any{
"m.fully_read": eventID,
"m.read": eventID,
}), http.StatusOK)
result := ts.sync(alice, since)
room := result.Rooms.Join[roomID]
if !contains(typesOf(room.AccountData.Events), "m.fully_read") {
t.Errorf("room account data = %v, want m.fully_read", typesOf(room.AccountData.Events))
}
if _, ok := ephemeralEvent(result, roomID, "m.receipt"); !ok {
t.Error("the m.read in the same request should have become a receipt")
}
}
func TestReadMarkersNeedsAtLeastOneMarker(t *testing.T) {
ts := newTestServer(t, nil)
alice := ts.register("alice", "correct-horse-battery-staple")
roomID := ts.createRoom(alice, nil)
rec := ts.post("/_matrix/client/v3/rooms/"+url.PathEscape(roomID)+"/read_markers",
alice.AccessToken, map[string]any{})
expectError(t, rec, http.StatusBadRequest, "M_MISSING_PARAM")
}
func TestSendToDeviceReachesTheDeviceAndIsThenDrained(t *testing.T) {
ts := newTestServer(t, nil)
alice := ts.register("alice", "correct-horse-battery-staple")
bob := ts.register("bob", "hunter2-hunter2-hunter2")
bobSince := ts.sync(bob, "").NextBatch
expectStatus(t, ts.put("/_matrix/client/v3/sendToDevice/m.room_key/txn1",
alice.AccessToken, map[string]any{
"messages": map[string]any{
bob.UserID: map[string]any{
bob.DeviceID: map[string]any{"session_id": "abc"},
},
},
}), http.StatusOK)
delivered := ts.sync(bob, bobSince)
if len(delivered.ToDevice.Events) != 1 {
t.Fatalf("to_device = %+v, want one message", delivered.ToDevice.Events)
}
msg := delivered.ToDevice.Events[0]
if msg.Type != "m.room_key" || msg.Sender != alice.UserID {
t.Errorf("to_device event = %+v, want an m.room_key from %s", msg, alice.UserID)
}
if msg.Content["session_id"] != "abc" {
t.Errorf("content = %+v, want the body as it was sent", msg.Content)
}
// Syncing past the batch acknowledges it; the next sync must not
// deliver it again.
again := ts.sync(bob, delivered.NextBatch)
if len(again.ToDevice.Events) != 0 {
t.Errorf("to_device = %+v, want nothing after the batch was acknowledged", again.ToDevice.Events)
}
// Alice's own devices were not addressed and must see nothing.
aliceResult := ts.sync(alice, "")
if len(aliceResult.ToDevice.Events) != 0 {
t.Errorf("the sender received their own to-device message: %+v", aliceResult.ToDevice.Events)
}
}
func TestSendToDeviceWildcardAddressesEveryDevice(t *testing.T) {
ts := newTestServer(t, nil)
alice := ts.register("alice", "correct-horse-battery-staple")
bob := ts.register("bob", "hunter2-hunter2-hunter2")
bobSecond := ts.login(bob, "SECONDDEVICE")
firstSince := ts.sync(bob, "").NextBatch
secondSince := ts.sync(bobSecond, "").NextBatch
expectStatus(t, ts.put("/_matrix/client/v3/sendToDevice/m.room_key/txn1",
alice.AccessToken, map[string]any{
"messages": map[string]any{
bob.UserID: map[string]any{"*": map[string]any{"session_id": "shared"}},
},
}), http.StatusOK)
for _, session := range []struct {
name string
acc account
since string
}{
{"the first device", bob, firstSince},
{"the second device", bobSecond, secondSince},
} {
result := ts.sync(session.acc, session.since)
if len(result.ToDevice.Events) != 1 {
t.Errorf("%s got %+v, want one message", session.name, result.ToDevice.Events)
}
}
}
func TestSendToDeviceToARemoteUserIsDroppedNotRefused(t *testing.T) {
ts := newTestServer(t, nil)
alice := ts.register("alice", "correct-horse-battery-staple")
// Federation is off. Failing the request would stop the local
// deliveries in the same batch from happening at all.
expectStatus(t, ts.put("/_matrix/client/v3/sendToDevice/m.room_key/txn1",
alice.AccessToken, map[string]any{
"messages": map[string]any{
"@carol:elsewhere.example": map[string]any{"ANY": map[string]any{}},
},
}), http.StatusOK)
}
func TestPresenceRoundTrips(t *testing.T) {
ts := newTestServer(t, nil)
alice := ts.register("alice", "correct-horse-battery-staple")
expectStatus(t, ts.put("/_matrix/client/v3/presence/"+url.PathEscape(alice.UserID)+"/status",
alice.AccessToken, map[string]any{
"presence": "unavailable",
"status_msg": "in a meeting",
}), http.StatusOK)
rec := ts.get("/_matrix/client/v3/presence/"+url.PathEscape(alice.UserID)+"/status",
alice.AccessToken)
expectStatus(t, rec, http.StatusOK)
body := jsonBody(t, rec)
if body["presence"] != "unavailable" {
t.Errorf("presence = %v, want unavailable", body["presence"])
}
if body["status_msg"] != "in a meeting" {
t.Errorf("status_msg = %v, want \"in a meeting\"", body["status_msg"])
}
}
func TestPresenceOfAUserWhoNeverSetItIsOffline(t *testing.T) {
ts := newTestServer(t, nil)
alice := ts.register("alice", "correct-horse-battery-staple")
bob := ts.register("bob", "hunter2-hunter2-hunter2")
rec := ts.get("/_matrix/client/v3/presence/"+url.PathEscape(bob.UserID)+"/status",
alice.AccessToken)
expectStatus(t, rec, http.StatusOK)
if got := jsonBody(t, rec)["presence"]; got != "offline" {
t.Errorf("presence = %v, want offline", got)
}
}
func TestPresenceIsOnlyAboutTheCaller(t *testing.T) {
ts := newTestServer(t, nil)
alice := ts.register("alice", "correct-horse-battery-staple")
bob := ts.register("bob", "hunter2-hunter2-hunter2")
rec := ts.put("/_matrix/client/v3/presence/"+url.PathEscape(bob.UserID)+"/status",
alice.AccessToken, map[string]any{"presence": "online"})
expectError(t, rec, http.StatusForbidden, "M_FORBIDDEN")
}
func TestPresenceRejectsAnUnknownState(t *testing.T) {
ts := newTestServer(t, nil)
alice := ts.register("alice", "correct-horse-battery-staple")
rec := ts.put("/_matrix/client/v3/presence/"+url.PathEscape(alice.UserID)+"/status",
alice.AccessToken, map[string]any{"presence": "asleep"})
expectError(t, rec, http.StatusBadRequest, "M_INVALID_PARAM")
}
func TestPresenceReachesSomebodySharingARoom(t *testing.T) {
ts := newTestServer(t, nil)
alice := ts.register("alice", "correct-horse-battery-staple")
bob := ts.register("bob", "hunter2-hunter2-hunter2")
roomID := ts.createRoom(alice, map[string]any{"preset": "public_chat"})
expectStatus(t, ts.post("/_matrix/client/v3/rooms/"+url.PathEscape(roomID)+"/join",
bob.AccessToken, map[string]any{}), http.StatusOK)
since := ts.sync(alice, "").NextBatch
expectStatus(t, ts.put("/_matrix/client/v3/presence/"+url.PathEscape(bob.UserID)+"/status",
bob.AccessToken, map[string]any{"presence": "unavailable", "status_msg": "away"}),
http.StatusOK)
result := ts.sync(alice, since)
var found bool
for _, e := range result.Presence.Events {
if e.Sender == bob.UserID && e.Content["presence"] == "unavailable" {
found = true
}
}
if !found {
t.Errorf("presence = %+v, want %s reported as unavailable", result.Presence.Events, bob.UserID)
}
}
+5 -23
View File
@@ -479,32 +479,14 @@ func TestCapabilities(t *testing.T) {
}
}
// TestSyncPlaceholder documents what the Phase 1 /sync does: it answers a
// valid token with an empty, well-formed response, and refuses a revoked
// one. Phase 4 replaces it with the real syncapi.
func TestSyncPlaceholder(t *testing.T) {
ts := newTestServer(t, nil)
acc := ts.register("alice", "superuser")
rec := ts.get("/_matrix/client/v3/sync", acc.AccessToken)
expectStatus(t, rec, http.StatusOK)
body := jsonBody(t, rec)
if next, _ := body["next_batch"].(string); next == "" {
t.Error("/sync must return a next_batch token")
}
rooms, _ := body["rooms"].(map[string]any)
for _, key := range []string{"join", "invite", "leave"} {
if _, present := rooms[key]; !present {
t.Errorf("rooms is missing %s: %s", key, rec.Body.String())
}
}
}
func TestUnknownClientEndpoint(t *testing.T) {
ts := newTestServer(t, nil)
rec := ts.get("/_matrix/client/v3/rooms/!a:b/messages", "")
// A real endpoint this build does not serve: third-party protocols
// belong to the application service API of PLAN.md phase 9. The spec's
// answer for an endpoint a server does not implement is
// M_UNRECOGNIZED, and the router's catch-all is what gives it.
rec := ts.get("/_matrix/client/v3/thirdparty/protocols", "")
expectError(t, rec, http.StatusNotFound, "M_UNRECOGNIZED")
}
+344
View File
@@ -0,0 +1,344 @@
package clientapi_test
import (
"fmt"
"net/http"
"net/url"
"testing"
)
// /messages and /context: a room's history, which is the other half of the
// read model. The thing worth pinning down is that paging terminates and
// that it loses nothing — a client that pages from the bottom of a room to
// the top must see every event exactly once.
type messagesResult struct {
Start string `json:"start"`
End string `json:"end"`
Chunk []syncEvent `json:"chunk"`
State []syncEvent `json:"state"`
}
// messages performs one /messages call.
func (ts *testServer) messages(acc account, roomID string, query url.Values) messagesResult {
ts.t.Helper()
path := "/_matrix/client/v3/rooms/" + url.PathEscape(roomID) + "/messages"
if encoded := query.Encode(); encoded != "" {
path += "?" + encoded
}
rec := ts.get(path, acc.AccessToken)
expectStatus(ts.t, rec, http.StatusOK)
return decode[messagesResult](ts.t, rec)
}
func TestMessagesPagesBackwardsThroughTheWholeRoom(t *testing.T) {
ts := newTestServer(t, nil)
alice := ts.register("alice", "correct-horse-battery-staple")
roomID := ts.createRoom(alice, nil)
const messages = 7
for i := range messages {
ts.sendMessage(alice, roomID, fmt.Sprintf("line %d", i))
}
// Page backwards in twos until the server stops handing out a token.
var (
seen []string
from string
pages int
)
for {
query := url.Values{"dir": {"b"}, "limit": {"2"}}
if from != "" {
query.Set("from", from)
}
page := ts.messages(alice, roomID, query)
seen = append(seen, bodiesOf(page.Chunk)...)
pages++
if pages > 20 {
t.Fatal("paging backwards did not terminate")
}
if page.End == "" {
break
}
if len(page.Chunk) == 0 {
t.Fatalf("page %d was empty but carried an end token %q", pages, page.End)
}
from = page.End
}
// Every message exactly once. The order is newest first within a page
// and the pages walk backwards, so the whole set is what matters here;
// the ordering inside a page is covered below.
if len(seen) != messages {
t.Fatalf("saw %d messages over %d pages, want %d: %v", len(seen), pages, messages, seen)
}
counts := map[string]int{}
for _, body := range seen {
counts[body]++
}
for i := range messages {
body := fmt.Sprintf("line %d", i)
if counts[body] != 1 {
t.Errorf("%q appeared %d times, want once", body, counts[body])
}
}
}
func TestMessagesBackwardsStartsAtTheNewestEvent(t *testing.T) {
ts := newTestServer(t, nil)
alice := ts.register("alice", "correct-horse-battery-staple")
roomID := ts.createRoom(alice, nil)
ts.sendMessage(alice, roomID, "older")
ts.sendMessage(alice, roomID, "newest")
page := ts.messages(alice, roomID, url.Values{"dir": {"b"}, "limit": {"1"}})
got := bodiesOf(page.Chunk)
if len(got) != 1 || got[0] != "newest" {
t.Errorf("chunk = %v, want [newest]: a backwards page with no ?from= starts at the end of the room", got)
}
}
func TestMessagesForwardsFromTheStartOfTheRoom(t *testing.T) {
ts := newTestServer(t, nil)
alice := ts.register("alice", "correct-horse-battery-staple")
roomID := ts.createRoom(alice, nil)
ts.sendMessage(alice, roomID, "first")
ts.sendMessage(alice, roomID, "second")
page := ts.messages(alice, roomID, url.Values{"dir": {"f"}, "limit": {"100"}})
got := typesOf(page.Chunk)
if len(got) == 0 || got[0] != "m.room.create" {
t.Fatalf("chunk starts with %v, want the create event first", got)
}
bodies := bodiesOf(page.Chunk)
if len(bodies) != 2 || bodies[0] != "first" || bodies[1] != "second" {
t.Errorf("bodies = %v, want [first second] in order", bodies)
}
}
func TestMessagesClosesTheGapASyncReported(t *testing.T) {
ts := newTestServer(t, nil)
alice := ts.register("alice", "correct-horse-battery-staple")
roomID := ts.createRoom(alice, nil)
for i := range 5 {
ts.sendMessage(alice, roomID, fmt.Sprintf("line %d", i))
}
// A sync with a tight limit leaves a gap and hands back the token to
// close it with. That token has to be a valid ?from= here: it is the
// whole reason the two endpoints share a token format.
result := ts.syncWith(alice, url.Values{
"filter": {`{"room":{"timeline":{"limit":2}}}`},
})
room := result.Rooms.Join[roomID]
if !room.Timeline.Limited || room.Timeline.PrevBatch == "" {
t.Fatalf("expected a limited timeline with a prev_batch, got %+v", room.Timeline)
}
page := ts.messages(alice, roomID, url.Values{
"dir": {"b"},
"from": {room.Timeline.PrevBatch},
"limit": {"10"},
})
// Nothing the sync already showed may appear again.
synced := map[string]bool{}
for _, e := range room.Timeline.Events {
synced[e.EventID] = true
}
for _, e := range page.Chunk {
if synced[e.EventID] {
t.Errorf("%s was in both the sync and the page that was meant to precede it", e.EventID)
}
}
if len(page.Chunk) == 0 {
t.Error("the page closing the gap was empty")
}
}
func TestMessagesAppliesAFilter(t *testing.T) {
ts := newTestServer(t, nil)
alice := ts.register("alice", "correct-horse-battery-staple")
roomID := ts.createRoom(alice, nil)
ts.sendMessage(alice, roomID, "a message")
page := ts.messages(alice, roomID, url.Values{
"dir": {"b"},
"limit": {"50"},
"filter": {`{"types":["m.room.message"]}`},
})
for _, e := range page.Chunk {
if e.Type != "m.room.message" {
t.Errorf("chunk contains %s, want only m.room.message", e.Type)
}
}
if len(page.Chunk) != 1 {
t.Errorf("chunk has %d events, want the one message", len(page.Chunk))
}
}
func TestMessagesRejectsABadDirection(t *testing.T) {
ts := newTestServer(t, nil)
alice := ts.register("alice", "correct-horse-battery-staple")
roomID := ts.createRoom(alice, nil)
rec := ts.get("/_matrix/client/v3/rooms/"+url.PathEscape(roomID)+"/messages?dir=sideways",
alice.AccessToken)
expectError(t, rec, http.StatusBadRequest, "M_INVALID_PARAM")
}
func TestMessagesRefusesANonMember(t *testing.T) {
ts := newTestServer(t, nil)
alice := ts.register("alice", "correct-horse-battery-staple")
bob := ts.register("bob", "hunter2-hunter2-hunter2")
// A private room: nothing about it is world-readable.
roomID := ts.createRoom(alice, map[string]any{"preset": "private_chat"})
rec := ts.get("/_matrix/client/v3/rooms/"+url.PathEscape(roomID)+"/messages?dir=b",
bob.AccessToken)
expectError(t, rec, http.StatusForbidden, "M_FORBIDDEN")
}
type contextResult struct {
Start string `json:"start"`
End string `json:"end"`
EventsBefore []syncEvent `json:"events_before"`
Event syncEvent `json:"event"`
EventsAfter []syncEvent `json:"events_after"`
State []syncEvent `json:"state"`
}
func TestContextReturnsTheEventAndItsSurroundings(t *testing.T) {
ts := newTestServer(t, nil)
alice := ts.register("alice", "correct-horse-battery-staple")
roomID := ts.createRoom(alice, nil)
ts.sendMessage(alice, roomID, "before 1")
ts.sendMessage(alice, roomID, "before 2")
target := ts.sendMessage(alice, roomID, "the target")
ts.sendMessage(alice, roomID, "after 1")
ts.sendMessage(alice, roomID, "after 2")
rec := ts.get(fmt.Sprintf("/_matrix/client/v3/rooms/%s/context/%s?limit=5",
url.PathEscape(roomID), url.PathEscape(target)), alice.AccessToken)
expectStatus(t, rec, http.StatusOK)
result := decode[contextResult](t, rec)
if result.Event.EventID != target {
t.Errorf("event = %s, want %s", result.Event.EventID, target)
}
// events_before is newest first, so the message immediately before
// the target comes first.
before := bodiesOf(result.EventsBefore)
if len(before) == 0 || before[0] != "before 2" {
t.Errorf("events_before = %v, want it to start with \"before 2\"", before)
}
after := bodiesOf(result.EventsAfter)
if len(after) == 0 || after[0] != "after 1" {
t.Errorf("events_after = %v, want it to start with \"after 1\"", after)
}
if result.Start == "" || result.End == "" {
t.Error("a context must carry both paging tokens")
}
if len(result.State) == 0 {
t.Error("a context must carry the state needed to render its chunk")
}
}
func TestContextStateIsLazyLoadedWhenAsked(t *testing.T) {
ts := newTestServer(t, nil)
alice := ts.register("alice", "correct-horse-battery-staple")
roomID := ts.createRoom(alice, nil)
target := ts.sendMessage(alice, roomID, "only one speaker")
rec := ts.get(fmt.Sprintf("/_matrix/client/v3/rooms/%s/context/%s?filter=%s",
url.PathEscape(roomID), url.PathEscape(target),
url.QueryEscape(`{"lazy_load_members":true}`)), alice.AccessToken)
expectStatus(t, rec, http.StatusOK)
result := decode[contextResult](t, rec)
for _, e := range result.State {
if e.Type != "m.room.member" {
t.Errorf("lazy-loaded state contains %s, want only member events", e.Type)
}
}
if len(result.State) != 1 {
t.Errorf("state has %d events, want just the one sender's member event", len(result.State))
}
}
func TestContextOfAnUnknownEventIsNotFound(t *testing.T) {
ts := newTestServer(t, nil)
alice := ts.register("alice", "correct-horse-battery-staple")
roomID := ts.createRoom(alice, nil)
rec := ts.get("/_matrix/client/v3/rooms/"+url.PathEscape(roomID)+"/context/$nope",
alice.AccessToken)
expectError(t, rec, http.StatusNotFound, "M_NOT_FOUND")
}
func TestMessagesBackwardsChunkIsNewestFirst(t *testing.T) {
ts := newTestServer(t, nil)
alice := ts.register("alice", "correct-horse-battery-staple")
roomID := ts.createRoom(alice, nil)
ts.sendMessage(alice, roomID, "first")
ts.sendMessage(alice, roomID, "second")
ts.sendMessage(alice, roomID, "third")
// The spec says a backwards page is in reverse chronological order,
// because that is the order a client scrolling up consumes it in.
page := ts.messages(alice, roomID, url.Values{
"dir": {"b"},
"limit": {"50"},
"filter": {`{"types":["m.room.message"]}`},
})
got := bodiesOf(page.Chunk)
want := []string{"third", "second", "first"}
if len(got) != len(want) {
t.Fatalf("chunk = %v, want %v", got, want)
}
for i := range got {
if got[i] != want[i] {
t.Fatalf("chunk = %v, want %v", got, want)
}
}
// Forwards is the other way round.
forwards := ts.messages(alice, roomID, url.Values{
"dir": {"f"},
"limit": {"50"},
"filter": {`{"types":["m.room.message"]}`},
})
if got := bodiesOf(forwards.Chunk); len(got) == 0 || got[0] != "first" {
t.Errorf("forwards chunk = %v, want it to start with \"first\"", got)
}
}
func TestMessagesStartNamesWhereThePageActuallyBegan(t *testing.T) {
ts := newTestServer(t, nil)
alice := ts.register("alice", "correct-horse-battery-staple")
roomID := ts.createRoom(alice, nil)
ts.sendMessage(alice, roomID, "only")
// ?from= is optional. Without it, `start` has to name the end of the
// room the page began at: a client that paged backwards and then used
// `start` to page forwards again would otherwise be handed the whole
// room a second time.
page := ts.messages(alice, roomID, url.Values{"dir": {"b"}, "limit": {"50"}})
if page.Start == "" || page.Start == "s0" {
t.Fatalf("start = %q, want the position the page began at", page.Start)
}
forwards := ts.messages(alice, roomID, url.Values{
"dir": {"f"},
"from": {page.Start},
"limit": {"50"},
})
if len(forwards.Chunk) != 0 {
t.Errorf("paging forwards from the end returned %d events, want none",
len(forwards.Chunk))
}
}
+12 -6
View File
@@ -313,12 +313,10 @@ type membersResponse struct {
// handleGetMembers implements GET /_matrix/client/v3/rooms/{roomID}/members.
//
// The ?at= parameter asks for the membership as of a point in the event
// stream, and is accepted and ignored. That is not a shortcut: there is one
// stream position in this build, because /sync has no stream to be at until
// Phase 4, so the membership as of any token a client can hold *is* the
// current membership. Phase 4 replaces this endpoint's filtering along with
// /sync and has to honour it then — see docs/rooms.md.
// The ?at= parameter is a sync token, and names the point in the event
// stream to report the membership as of. A client rendering an older part
// of a room's timeline needs it: the names and avatars to show against
// those messages are the ones their senders had then, not now.
func (c *ClientAPI) handleGetMembers(w http.ResponseWriter, r *http.Request, auth userapi.Authenticated) error {
roomID, err := pathRoomID(r)
if err != nil {
@@ -333,11 +331,19 @@ func (c *ClientAPI) handleGetMembers(w http.ResponseWriter, r *http.Request, aut
}
}
// ?at= only has a meaning once there is a stream, so it is read here
// rather than in the roomserver: the token format is the syncapi's.
at, err := ParseSyncPosition(query.Get("at"))
if err != nil {
return err
}
members, err := c.rooms.Members(r.Context(), roomserver.MembersRequest{
RoomID: roomID,
User: auth.UserID,
Membership: membership,
NotMembership: notMembership,
At: at,
})
if err != nil {
return roomError(err)
+3 -3
View File
@@ -252,9 +252,9 @@ func TestMembershipEndpoints(t *testing.T) {
bob.AccessToken)
expectError(t, rec, http.StatusBadRequest, httputil.ErrCodeBadJSON)
// ?at= is accepted and ignored: there is one stream position in this
// build, so the membership as of any token a client can hold is the
// current membership. Phase 4 has to honour it properly.
// ?at= names a stream position to report the membership as of; the
// zero token is the start of the room, which every member postdates.
// TestMembersAtAnEarlierPosition covers what it actually returns.
rec = ts.get("/_matrix/client/v3/rooms/"+escaped+"/members?at=s0_0", bob.AccessToken)
expectStatus(t, rec, http.StatusOK)
+249 -59
View File
@@ -1,74 +1,264 @@
package clientapi
import (
"encoding/json"
"errors"
"net/http"
"strconv"
"time"
"github.com/dariuszjaniak/warp/server/internal/httputil"
"github.com/dariuszjaniak/warp/server/internal/storage"
"github.com/dariuszjaniak/warp/server/internal/syncapi"
"github.com/dariuszjaniak/warp/server/internal/userapi"
)
// syncResponse is the subset of the /sync body this build can fill in.
type syncResponse struct {
NextBatch string `json:"next_batch"`
Rooms syncRooms `json:"rooms"`
Presence syncEventList `json:"presence"`
AccountData syncEventList `json:"account_data"`
ToDevice syncEventList `json:"to_device"`
DeviceLists syncDeviceLists `json:"device_lists"`
}
type syncRooms struct {
Join map[string]any `json:"join"`
Invite map[string]any `json:"invite"`
Leave map[string]any `json:"leave"`
Knock map[string]any `json:"knock"`
}
type syncEventList struct {
Events []any `json:"events"`
}
type syncDeviceLists struct {
Changed []string `json:"changed"`
Left []string `json:"left"`
}
// syncPlaceholderToken is the only stream position this build has.
// syncError maps a syncapi error onto the Matrix error the spec answers it
// with.
//
// It is a real token shape rather than an empty string so that a client
// storing it and sending it back as ?since= gets the same answer.
const syncPlaceholderToken = "s0_0"
// It defers to roomError for everything that came out of the roomserver,
// which is most of it: a sync read is mostly room reads, and the two have
// to answer "unknown room" the same way whichever endpoint asked.
func syncError(err error) error {
var matrixErr *httputil.MatrixError
switch {
case err == nil:
return nil
case errors.As(err, &matrixErr):
return err
// handleSync implements GET /_matrix/client/v3/sync as far as this build
// can.
case errors.Is(err, syncapi.ErrNoSuchFilter):
return httputil.NotFound("Unknown filter")
case errors.Is(err, syncapi.ErrInvalidFilter),
errors.Is(err, syncapi.ErrInvalidParam):
return httputil.InvalidParam("%s", err.Error())
case errors.Is(err, syncapi.ErrInvalidToken):
return httputil.InvalidParam("%s", err.Error())
case errors.Is(err, syncapi.ErrPresenceDisabled):
return httputil.Forbidden("Presence is disabled on this server")
default:
return roomError(err)
}
}
// handleSync implements GET /_matrix/client/v3/sync.
//
// It is a placeholder, and since Phase 3 it is an incomplete answer rather
// than a complete one: there are rooms now, and this reports none of them.
// Filling it in means the event stream — stream tokens, incremental deltas,
// long polling, filters and lazy-loaded members — which is the syncapi of
// PLAN.md phase 4, and which replaces this wholesale.
//
// It stays because of what it does buy: a valid token syncs and a revoked
// one does not, which is the first thing every client and the test suite
// check, and which cannot be observed at all without an endpoint here. A
// client can meanwhile see its rooms through /joined_rooms and read them
// through /rooms/{roomID}/state. See docs/rooms.md.
func (c *ClientAPI) handleSync(w http.ResponseWriter, _ *http.Request, _ userapi.Authenticated) error {
// The `timeout` parameter is ignored rather than honoured: blocking for
// 30 seconds to return a response this build cannot change would hold a
// connection open for nothing.
httputil.WriteJSON(w, http.StatusOK, syncResponse{
NextBatch: syncPlaceholderToken,
Rooms: syncRooms{
Join: map[string]any{},
Invite: map[string]any{},
Leave: map[string]any{},
Knock: map[string]any{},
},
Presence: syncEventList{Events: []any{}},
AccountData: syncEventList{Events: []any{}},
ToDevice: syncEventList{Events: []any{}},
DeviceLists: syncDeviceLists{Changed: []string{}, Left: []string{}},
// It is the one endpoint that is expected to block. The handler holds the
// request open for up to the configured long-poll timeout, and the syncapi
// returns as soon as anything the client cares about happens — so the
// timeout decides how often an idle client re-establishes its request, not
// how quickly it hears about a message.
func (c *ClientAPI) handleSync(w http.ResponseWriter, r *http.Request, auth userapi.Authenticated) error {
query := r.URL.Query()
timeout, err := durationParam(query.Get("timeout"))
if err != nil {
return err
}
fullState, err := boolParam(query.Get("full_state"))
if err != nil {
return err
}
resp, err := c.sync.Sync(r.Context(), syncapi.SyncRequest{
User: auth.UserID,
Localpart: auth.Localpart,
Device: auth.DeviceID,
Since: query.Get("since"),
Filter: query.Get("filter"),
Timeout: timeout,
FullState: fullState,
SetPresence: query.Get("set_presence"),
})
if err != nil {
// A client that gives up on a long poll cancels the request, which
// arrives here as a context error. Writing a response to a
// connection nobody is reading would be the only thing a handler
// could do about it, so the request is simply dropped.
if ctxErr := r.Context().Err(); ctxErr != nil && errors.Is(err, ctxErr) {
return nil //nolint:nilerr // the client is gone; there is nobody to answer
}
return syncError(err)
}
// A sync response is never cached: it is a position in a stream, and a
// cached one would hand a client the same batch twice.
httputil.NoCache(w)
httputil.WriteJSON(w, http.StatusOK, resp)
return nil
}
// handleMessages implements GET /_matrix/client/v3/rooms/{roomID}/messages.
func (c *ClientAPI) handleMessages(w http.ResponseWriter, r *http.Request, auth userapi.Authenticated) error {
roomID, err := pathRoomID(r)
if err != nil {
return err
}
query := r.URL.Query()
direction := storage.DirectionBackward
switch query.Get("dir") {
case "f":
direction = storage.DirectionForward
case "b", "":
// The spec makes `dir` required; a client that leaves it out means
// "scroll up", which is what every one of them is doing.
default:
return httputil.InvalidParam("dir must be \"b\" or \"f\"")
}
limit, err := intParam(query.Get("limit"))
if err != nil {
return err
}
resp, err := c.sync.Messages(r.Context(), syncapi.MessagesRequest{
RoomID: roomID,
User: auth.UserID,
Localpart: auth.Localpart,
From: query.Get("from"),
To: query.Get("to"),
Direction: direction,
Limit: limit,
Filter: query.Get("filter"),
})
if err != nil {
return syncError(err)
}
httputil.WriteJSON(w, http.StatusOK, resp)
return nil
}
// handleContext implements
// GET /_matrix/client/v3/rooms/{roomID}/context/{eventID}.
func (c *ClientAPI) handleContext(w http.ResponseWriter, r *http.Request, auth userapi.Authenticated) error {
roomID, err := pathRoomID(r)
if err != nil {
return err
}
eventID := r.PathValue("eventID")
if eventID == "" {
return httputil.MissingParam("An event ID is required")
}
limit, err := intParam(r.URL.Query().Get("limit"))
if err != nil {
return err
}
resp, err := c.sync.Context(r.Context(), syncapi.ContextRequest{
RoomID: roomID,
EventID: eventID,
User: auth.UserID,
Localpart: auth.Localpart,
Limit: limit,
Filter: r.URL.Query().Get("filter"),
})
if err != nil {
return syncError(err)
}
httputil.WriteJSON(w, http.StatusOK, resp)
return nil
}
// filterResponse is what POST /user/{userID}/filter returns.
type filterResponse struct {
FilterID string `json:"filter_id"`
}
// handlePostFilter implements POST /_matrix/client/v3/user/{userID}/filter.
func (c *ClientAPI) handlePostFilter(w http.ResponseWriter, r *http.Request, auth userapi.Authenticated) error {
localpart, err := c.requireOwnAccountData(auth, r.PathValue("userID"))
if err != nil {
return err
}
// The filter is stored and returned byte for byte, so it is read as
// raw JSON rather than decoded and re-encoded: a client that compares
// what it gets back with what it sent must see the same thing.
var body json.RawMessage
if err := httputil.DecodeJSON(w, r, &body); err != nil {
return err
}
filterID, err := c.sync.SaveFilter(r.Context(), localpart, body)
if err != nil {
return syncError(err)
}
httputil.WriteJSON(w, http.StatusOK, filterResponse{FilterID: filterID})
return nil
}
// handleGetFilter implements
// GET /_matrix/client/v3/user/{userID}/filter/{filterID}.
func (c *ClientAPI) handleGetFilter(w http.ResponseWriter, r *http.Request, auth userapi.Authenticated) error {
localpart, err := c.requireOwnAccountData(auth, r.PathValue("userID"))
if err != nil {
return err
}
filterID := r.PathValue("filterID")
if filterID == "" {
return httputil.MissingParam("A filter ID is required")
}
stored, err := c.sync.StoredFilter(r.Context(), localpart, filterID)
if err != nil {
return syncError(err)
}
httputil.WriteRawJSON(w, http.StatusOK, stored)
return nil
}
// ParseSyncPosition reads a sync token from a query parameter and returns
// the event-stream position in it, or 0 for an absent one.
//
// It lives here rather than in the roomserver because the token format is
// the syncapi's, and /rooms/{id}/members?at= is the one room endpoint that
// takes one.
func ParseSyncPosition(raw string) (int64, error) {
if raw == "" {
return 0, nil
}
token, err := syncapi.ParseToken(raw)
if err != nil {
return 0, httputil.InvalidParam("%v", err)
}
return token.PDU, nil
}
// durationParam reads a millisecond duration from a query parameter.
func durationParam(raw string) (time.Duration, error) {
if raw == "" {
return 0, nil
}
ms, err := strconv.ParseInt(raw, 10, 64)
if err != nil || ms < 0 {
return 0, httputil.InvalidParam("timeout must be a non-negative number of milliseconds")
}
return time.Duration(ms) * time.Millisecond, nil
}
// intParam reads a non-negative integer from a query parameter.
func intParam(raw string) (int, error) {
if raw == "" {
return 0, nil
}
value, err := strconv.Atoi(raw)
if err != nil || value < 0 {
return 0, httputil.InvalidParam("limit must be a non-negative integer")
}
return value, nil
}
// boolParam reads a boolean from a query parameter.
func boolParam(raw string) (bool, error) {
if raw == "" {
return false, nil
}
value, err := strconv.ParseBool(raw)
if err != nil {
return false, httputil.InvalidParam("%q is not a boolean", raw)
}
return value, nil
}
+664
View File
@@ -0,0 +1,664 @@
package clientapi_test
import (
"fmt"
"net/http"
"net/url"
"testing"
"time"
)
// The /sync tests. They go through HTTP rather than calling the syncapi
// directly, because what is worth pinning down is the response a client
// sees: the shape of the body, which section a room lands in, and whether a
// token handed back can be handed in again.
// syncResult is the handful of things these tests read out of a response.
// It is a typed struct rather than a map because a sync response is nested
// four deep, and `body["rooms"].(map[string]any)["join"]` repeated thirty
// times is unreadable.
type syncResult struct {
NextBatch string `json:"next_batch"`
Rooms struct {
Join map[string]struct {
Timeline struct {
Events []syncEvent `json:"events"`
Limited bool `json:"limited"`
PrevBatch string `json:"prev_batch"`
} `json:"timeline"`
State struct {
Events []syncEvent `json:"events"`
} `json:"state"`
Ephemeral struct {
Events []syncEvent `json:"events"`
} `json:"ephemeral"`
AccountData struct {
Events []syncEvent `json:"events"`
} `json:"account_data"`
Summary *struct {
Heroes []string `json:"m.heroes"`
JoinedMemberCount int `json:"m.joined_member_count"`
InvitedMemberCount int `json:"m.invited_member_count"`
} `json:"summary"`
} `json:"join"`
Invite map[string]struct {
InviteState struct {
Events []syncEvent `json:"events"`
} `json:"invite_state"`
} `json:"invite"`
Leave map[string]struct {
Timeline struct {
Events []syncEvent `json:"events"`
} `json:"timeline"`
State struct {
Events []syncEvent `json:"events"`
} `json:"state"`
} `json:"leave"`
} `json:"rooms"`
Presence struct {
Events []syncEvent `json:"events"`
} `json:"presence"`
AccountData struct {
Events []syncEvent `json:"events"`
} `json:"account_data"`
ToDevice struct {
Events []syncEvent `json:"events"`
} `json:"to_device"`
DeviceLists struct {
Changed []string `json:"changed"`
Left []string `json:"left"`
} `json:"device_lists"`
}
type syncEvent struct {
EventID string `json:"event_id"`
RoomID string `json:"room_id"`
Type string `json:"type"`
StateKey *string `json:"state_key"`
Sender string `json:"sender"`
Content map[string]any `json:"content"`
}
// sync performs one /sync, with no timeout: every test but the long-poll
// ones wants the answer as it stands.
func (ts *testServer) sync(acc account, since string) syncResult {
ts.t.Helper()
return ts.syncWith(acc, url.Values{"since": {since}})
}
// syncWith performs a /sync with arbitrary query parameters.
func (ts *testServer) syncWith(acc account, query url.Values) syncResult {
ts.t.Helper()
path := "/_matrix/client/v3/sync"
if encoded := query.Encode(); encoded != "" {
path += "?" + encoded
}
rec := ts.get(path, acc.AccessToken)
expectStatus(ts.t, rec, http.StatusOK)
result := decode[syncResult](ts.t, rec)
if result.NextBatch == "" {
ts.t.Fatalf("/sync returned no next_batch: %s", rec.Body.String())
}
return result
}
// sendMessage sends an m.room.message and returns its event ID.
func (ts *testServer) sendMessage(acc account, roomID, body string) string {
ts.t.Helper()
path := fmt.Sprintf("/_matrix/client/v3/rooms/%s/send/m.room.message/%s",
url.PathEscape(roomID), url.PathEscape(fmt.Sprintf("txn-%s-%d", body, time.Now().UnixNano())))
rec := ts.put(path, acc.AccessToken, map[string]any{"msgtype": "m.text", "body": body})
expectStatus(ts.t, rec, http.StatusOK)
eventID, _ := jsonBody(ts.t, rec)["event_id"].(string)
if eventID == "" {
ts.t.Fatalf("send returned no event ID: %s", rec.Body.String())
}
return eventID
}
// bodiesOf projects timeline events onto their message bodies, which is
// what most of these tests actually assert on.
func bodiesOf(events []syncEvent) []string {
out := make([]string, 0, len(events))
for _, e := range events {
if body, ok := e.Content["body"].(string); ok {
out = append(out, body)
}
}
return out
}
// typesOf projects events onto their types.
func typesOf(events []syncEvent) []string {
out := make([]string, 0, len(events))
for _, e := range events {
out = append(out, e.Type)
}
return out
}
func contains(haystack []string, needle string) bool {
for _, s := range haystack {
if s == needle {
return true
}
}
return false
}
func TestSyncInitialReportsTheRoomAndItsHistory(t *testing.T) {
ts := newTestServer(t, nil)
alice := ts.register("alice", "correct-horse-battery-staple")
roomID := ts.createRoom(alice, map[string]any{"name": "Rome"})
ts.sendMessage(alice, roomID, "hello")
result := ts.sync(alice, "")
room, ok := result.Rooms.Join[roomID]
if !ok {
t.Fatalf("the room is not in the join section: %+v", result.Rooms.Join)
}
if got := bodiesOf(room.Timeline.Events); !contains(got, "hello") {
t.Errorf("timeline bodies = %v, want it to contain \"hello\"", got)
}
// The room was created and filled in fewer events than the default
// timeline limit, so the whole of it is in the timeline and there is
// nothing before it to report as state.
if room.Timeline.Limited {
t.Error("a room shorter than the timeline limit must not be reported as limited")
}
// A sync's events carry no room_id: they are already nested under the
// room they belong to.
for _, e := range room.Timeline.Events {
if e.RoomID != "" {
t.Errorf("%s carries a room_id in a sync response", e.Type)
break
}
}
// device_lists is empty until Phase 7 and must still be present: a
// client reads a missing one as a malformed response.
if result.DeviceLists.Changed == nil || result.DeviceLists.Left == nil {
t.Error("device_lists must carry both lists even when empty")
}
}
func TestSyncIncrementalReturnsOnlyWhatIsNew(t *testing.T) {
ts := newTestServer(t, nil)
alice := ts.register("alice", "correct-horse-battery-staple")
roomID := ts.createRoom(alice, nil)
ts.sendMessage(alice, roomID, "first")
first := ts.sync(alice, "")
ts.sendMessage(alice, roomID, "second")
second := ts.sync(alice, first.NextBatch)
room, ok := second.Rooms.Join[roomID]
if !ok {
t.Fatalf("the room is not in the join section: %+v", second.Rooms.Join)
}
got := bodiesOf(room.Timeline.Events)
if len(got) != 1 || got[0] != "second" {
t.Errorf("timeline bodies = %v, want exactly [second]", got)
}
// An incremental sync with no gap reports no state: every state change
// in the window is a timeline event the client already has.
if len(room.State.Events) != 0 {
t.Errorf("state = %v, want none on a gapless incremental sync", typesOf(room.State.Events))
}
}
func TestSyncIncrementalIsEmptyWhenNothingHappened(t *testing.T) {
ts := newTestServer(t, nil)
alice := ts.register("alice", "correct-horse-battery-staple")
roomID := ts.createRoom(alice, nil)
first := ts.sync(alice, "")
second := ts.sync(alice, first.NextBatch)
if len(second.Rooms.Join) != 0 {
t.Errorf("join = %v, want nothing when nothing happened", second.Rooms.Join)
}
_ = roomID
}
func TestSyncTokenRoundTripsThroughTheClient(t *testing.T) {
ts := newTestServer(t, nil)
alice := ts.register("alice", "correct-horse-battery-staple")
roomID := ts.createRoom(alice, nil)
first := ts.sync(alice, "")
// Syncing twice from the same token must give the same answer: a token
// is a position, not a cursor the server advances for itself.
a := ts.sync(alice, first.NextBatch)
ts.sendMessage(alice, roomID, "once")
b := ts.sync(alice, first.NextBatch)
c := ts.sync(alice, first.NextBatch)
if len(a.Rooms.Join) != 0 {
t.Error("the first re-sync should have been empty")
}
if got := bodiesOf(b.Rooms.Join[roomID].Timeline.Events); len(got) != 1 {
t.Errorf("second re-sync timeline = %v, want one event", got)
}
if got := bodiesOf(c.Rooms.Join[roomID].Timeline.Events); len(got) != 1 {
t.Errorf("third re-sync timeline = %v, want the same one event", got)
}
}
func TestSyncRejectsAnUnreadableToken(t *testing.T) {
ts := newTestServer(t, nil)
alice := ts.register("alice", "correct-horse-battery-staple")
for _, since := range []string{"nonsense", "s-1", "sx", "s1_2_3_4_5_6"} {
rec := ts.get("/_matrix/client/v3/sync?since="+url.QueryEscape(since), alice.AccessToken)
expectError(t, rec, http.StatusBadRequest, "M_INVALID_PARAM")
}
}
func TestSyncAcceptsATokenFromAnOlderServer(t *testing.T) {
ts := newTestServer(t, nil)
alice := ts.register("alice", "correct-horse-battery-staple")
roomID := ts.createRoom(alice, nil)
ts.sendMessage(alice, roomID, "hello")
// A token with only the event position in it, as a client stored
// before the other streams existed. It must be read as "seen nothing"
// of those streams rather than refused.
result := ts.syncWith(alice, url.Values{"since": {"s1"}})
if len(result.Rooms.Join) == 0 {
t.Error("a short token must still sync")
}
}
func TestSyncLongPollWakesOnAnEvent(t *testing.T) {
ts := newTestServer(t, nil)
alice := ts.register("alice", "correct-horse-battery-staple")
roomID := ts.createRoom(alice, nil)
since := ts.sync(alice, "").NextBatch
done := make(chan syncResult, 1)
go func() {
done <- ts.syncWith(alice, url.Values{
"since": {since},
"timeout": {"10000"},
})
}()
// The sync has to be blocked before the event is sent, or it would
// find the event without ever having waited and the test would pass
// without testing anything.
waitForListener(t, ts)
ts.sendMessage(alice, roomID, "woken")
select {
case result := <-done:
got := bodiesOf(result.Rooms.Join[roomID].Timeline.Events)
if !contains(got, "woken") {
t.Errorf("timeline = %v, want it to contain \"woken\"", got)
}
case <-time.After(5 * time.Second):
t.Fatal("a blocked /sync was not woken by an event in its room")
}
}
func TestSyncLongPollReturnsEmptyOnTimeout(t *testing.T) {
ts := newTestServer(t, nil)
alice := ts.register("alice", "correct-horse-battery-staple")
ts.createRoom(alice, nil)
since := ts.sync(alice, "").NextBatch
start := time.Now()
result := ts.syncWith(alice, url.Values{"since": {since}, "timeout": {"150"}})
elapsed := time.Since(start)
if len(result.Rooms.Join) != 0 {
t.Errorf("join = %v, want nothing", result.Rooms.Join)
}
if elapsed < 100*time.Millisecond {
t.Errorf("a 150ms long poll returned after %v; it did not wait", elapsed)
}
}
// waitForListener blocks until a /sync has registered with the notifier, so
// that a test can be sure the sync it started is actually waiting.
func waitForListener(t *testing.T, ts *testServer) {
t.Helper()
deadline := time.Now().Add(5 * time.Second)
for time.Now().Before(deadline) {
if ts.syncAPI.Notifier().Listeners() > 0 {
return
}
time.Sleep(time.Millisecond)
}
t.Fatal("no /sync ever blocked on the notifier")
}
func TestSyncReportsAnInviteAsStrippedState(t *testing.T) {
ts := newTestServer(t, nil)
alice := ts.register("alice", "correct-horse-battery-staple")
bob := ts.register("bob", "hunter2-hunter2-hunter2")
roomID := ts.createRoom(alice, map[string]any{"name": "Carthage"})
rec := ts.post("/_matrix/client/v3/rooms/"+url.PathEscape(roomID)+"/invite",
alice.AccessToken, map[string]any{"user_id": bob.UserID})
expectStatus(t, rec, http.StatusOK)
result := ts.sync(bob, "")
invite, ok := result.Rooms.Invite[roomID]
if !ok {
t.Fatalf("the room is not in the invite section: %+v", result.Rooms.Invite)
}
if !contains(typesOf(invite.InviteState.Events), "m.room.name") {
t.Errorf("invite_state = %v, want it to name the room", typesOf(invite.InviteState.Events))
}
if !contains(typesOf(invite.InviteState.Events), "m.room.member") {
t.Error("invite_state must carry the member events that make the invite legible")
}
// An invitee gets no timeline at all: they are not a member.
if _, joined := result.Rooms.Join[roomID]; joined {
t.Error("an invited room must not be in the join section")
}
}
func TestSyncReportsALeaveAndThenStops(t *testing.T) {
ts := newTestServer(t, nil)
alice := ts.register("alice", "correct-horse-battery-staple")
bob := ts.register("bob", "hunter2-hunter2-hunter2")
roomID := ts.createRoom(alice, map[string]any{"preset": "public_chat"})
expectStatus(t, ts.post("/_matrix/client/v3/rooms/"+url.PathEscape(roomID)+"/join",
bob.AccessToken, map[string]any{}), http.StatusOK)
ts.sendMessage(alice, roomID, "while bob is here")
since := ts.sync(bob, "").NextBatch
expectStatus(t, ts.post("/_matrix/client/v3/rooms/"+url.PathEscape(roomID)+"/leave",
bob.AccessToken, map[string]any{}), http.StatusOK)
afterLeave := ts.sync(bob, since)
if _, ok := afterLeave.Rooms.Leave[roomID]; !ok {
t.Fatalf("the leave was not reported: %+v", afterLeave.Rooms)
}
// Everything after the leave is somebody else's business.
ts.sendMessage(alice, roomID, "after bob left")
quiet := ts.sync(bob, afterLeave.NextBatch)
for _, section := range []any{quiet.Rooms.Join[roomID], quiet.Rooms.Leave[roomID]} {
_ = section
}
if left, ok := quiet.Rooms.Leave[roomID]; ok {
if got := bodiesOf(left.Timeline.Events); contains(got, "after bob left") {
t.Errorf("a departed member was sent %v", got)
}
}
}
func TestSyncSummaryNamesARoomWithNoName(t *testing.T) {
ts := newTestServer(t, nil)
alice := ts.register("alice", "correct-horse-battery-staple")
bob := ts.register("bob", "hunter2-hunter2-hunter2")
roomID := ts.createRoom(alice, map[string]any{
"preset": "trusted_private_chat",
"invite": []string{bob.UserID},
})
result := ts.sync(alice, "")
room := result.Rooms.Join[roomID]
if room.Summary == nil {
t.Fatal("a room with no name must carry a summary to name it by")
}
if !contains(room.Summary.Heroes, bob.UserID) {
t.Errorf("heroes = %v, want it to name %s", room.Summary.Heroes, bob.UserID)
}
if room.Summary.JoinedMemberCount != 1 {
t.Errorf("joined_member_count = %d, want 1", room.Summary.JoinedMemberCount)
}
if room.Summary.InvitedMemberCount != 1 {
t.Errorf("invited_member_count = %d, want 1", room.Summary.InvitedMemberCount)
}
}
func TestSyncLimitedTimelineCarriesTheStateBeforeIt(t *testing.T) {
ts := newTestServer(t, nil)
alice := ts.register("alice", "correct-horse-battery-staple")
roomID := ts.createRoom(alice, nil)
since := ts.sync(alice, "").NextBatch
// A state change and then more messages than the timeline limit, so
// the state change falls into the gap and has to be reported
// separately.
expectStatus(t, ts.put("/_matrix/client/v3/rooms/"+url.PathEscape(roomID)+"/state/m.room.topic",
alice.AccessToken, map[string]any{"topic": "in the gap"}), http.StatusOK)
for i := range 5 {
ts.sendMessage(alice, roomID, fmt.Sprintf("message %d", i))
}
result := ts.syncWith(alice, url.Values{
"since": {since},
"filter": {`{"room":{"timeline":{"limit":2}}}`},
})
room := result.Rooms.Join[roomID]
if !room.Timeline.Limited {
t.Fatal("a timeline cut short by the limit must say so")
}
if room.Timeline.PrevBatch == "" {
t.Error("a limited timeline must carry a prev_batch to close the gap with")
}
if !contains(typesOf(room.State.Events), "m.room.topic") {
t.Errorf("state = %v, want the topic change that fell into the gap",
typesOf(room.State.Events))
}
}
func TestSyncFullStateReturnsEverythingAgain(t *testing.T) {
ts := newTestServer(t, nil)
alice := ts.register("alice", "correct-horse-battery-staple")
roomID := ts.createRoom(alice, map[string]any{"name": "Thebes"})
since := ts.sync(alice, "").NextBatch
result := ts.syncWith(alice, url.Values{
"since": {since},
"full_state": {"true"},
"filter": {`{"room":{"timeline":{"limit":1}}}`},
})
room, ok := result.Rooms.Join[roomID]
if !ok {
t.Fatalf("full_state must report every room: %+v", result.Rooms.Join)
}
if !contains(typesOf(room.State.Events), "m.room.create") {
t.Errorf("state = %v, want the whole state including m.room.create",
typesOf(room.State.Events))
}
}
func TestSyncLazyLoadingLeavesOutUninvolvedMembers(t *testing.T) {
ts := newTestServer(t, nil)
alice := ts.register("alice", "correct-horse-battery-staple")
bob := ts.register("bob", "hunter2-hunter2-hunter2")
roomID := ts.createRoom(alice, map[string]any{"preset": "public_chat"})
expectStatus(t, ts.post("/_matrix/client/v3/rooms/"+url.PathEscape(roomID)+"/join",
bob.AccessToken, map[string]any{}), http.StatusOK)
// Only Alice speaks, so only Alice's member event is needed to render
// the timeline.
for i := range 4 {
ts.sendMessage(alice, roomID, fmt.Sprintf("line %d", i))
}
result := ts.syncWith(alice, url.Values{
"filter": {`{"room":{"timeline":{"limit":2,"lazy_load_members":true}}}`},
})
room := result.Rooms.Join[roomID]
members := map[string]bool{}
for _, e := range room.State.Events {
if e.Type == "m.room.member" && e.StateKey != nil {
members[*e.StateKey] = true
}
}
if !members[alice.UserID] {
t.Error("lazy loading must still send the member event of a timeline sender")
}
if members[bob.UserID] {
t.Error("lazy loading must leave out a member who does not appear in the timeline")
}
}
func TestSyncAppliesATypeFilter(t *testing.T) {
ts := newTestServer(t, nil)
alice := ts.register("alice", "correct-horse-battery-staple")
roomID := ts.createRoom(alice, nil)
since := ts.sync(alice, "").NextBatch
ts.sendMessage(alice, roomID, "a message")
expectStatus(t, ts.put("/_matrix/client/v3/rooms/"+url.PathEscape(roomID)+"/state/m.room.topic",
alice.AccessToken, map[string]any{"topic": "a topic"}), http.StatusOK)
result := ts.syncWith(alice, url.Values{
"since": {since},
"filter": {`{"room":{"timeline":{"not_types":["m.room.message"]}}}`},
})
got := typesOf(result.Rooms.Join[roomID].Timeline.Events)
if contains(got, "m.room.message") {
t.Errorf("timeline = %v, want the message excluded", got)
}
if !contains(got, "m.room.topic") {
t.Errorf("timeline = %v, want the topic kept", got)
}
}
func TestSyncUsesAnUploadedFilter(t *testing.T) {
ts := newTestServer(t, nil)
alice := ts.register("alice", "correct-horse-battery-staple")
roomID := ts.createRoom(alice, nil)
rec := ts.post("/_matrix/client/v3/user/"+url.PathEscape(alice.UserID)+"/filter",
alice.AccessToken, map[string]any{
"room": map[string]any{
"timeline": map[string]any{"types": []string{"m.room.message"}},
},
})
expectStatus(t, rec, http.StatusOK)
filterID, _ := jsonBody(t, rec)["filter_id"].(string)
if filterID == "" {
t.Fatalf("no filter ID was returned: %s", rec.Body.String())
}
// It comes back exactly as it was uploaded.
rec = ts.get("/_matrix/client/v3/user/"+url.PathEscape(alice.UserID)+"/filter/"+filterID,
alice.AccessToken)
expectStatus(t, rec, http.StatusOK)
ts.sendMessage(alice, roomID, "kept")
result := ts.syncWith(alice, url.Values{"filter": {filterID}})
got := typesOf(result.Rooms.Join[roomID].Timeline.Events)
if !contains(got, "m.room.message") {
t.Errorf("timeline = %v, want the message", got)
}
if contains(got, "m.room.create") {
t.Errorf("timeline = %v, want only messages", got)
}
}
func TestGetUnknownFilterIsNotFound(t *testing.T) {
ts := newTestServer(t, nil)
alice := ts.register("alice", "correct-horse-battery-staple")
rec := ts.get("/_matrix/client/v3/user/"+url.PathEscape(alice.UserID)+"/filter/nope",
alice.AccessToken)
expectError(t, rec, http.StatusNotFound, "M_NOT_FOUND")
}
func TestFilterBelongsToItsOwner(t *testing.T) {
ts := newTestServer(t, nil)
alice := ts.register("alice", "correct-horse-battery-staple")
bob := ts.register("bob", "hunter2-hunter2-hunter2")
rec := ts.post("/_matrix/client/v3/user/"+url.PathEscape(bob.UserID)+"/filter",
alice.AccessToken, map[string]any{})
expectError(t, rec, http.StatusForbidden, "M_FORBIDDEN")
}
func TestSyncReportsAccountData(t *testing.T) {
ts := newTestServer(t, nil)
alice := ts.register("alice", "correct-horse-battery-staple")
since := ts.sync(alice, "").NextBatch
expectStatus(t, ts.put("/_matrix/client/v3/user/"+url.PathEscape(alice.UserID)+
"/account_data/m.direct", alice.AccessToken, map[string]any{"@bob:warp.example": []string{}}),
http.StatusOK)
result := ts.sync(alice, since)
if !contains(typesOf(result.AccountData.Events), "m.direct") {
t.Errorf("account_data = %v, want m.direct", typesOf(result.AccountData.Events))
}
// Account data is not an event: it has a type and a content and
// nothing else.
for _, e := range result.AccountData.Events {
if e.EventID != "" || e.Sender != "" {
t.Errorf("account data was reported as an event: %+v", e)
}
}
}
func TestMembersAtAnEarlierPosition(t *testing.T) {
ts := newTestServer(t, nil)
alice := ts.register("alice", "correct-horse-battery-staple")
bob := ts.register("bob", "hunter2-hunter2-hunter2")
roomID := ts.createRoom(alice, map[string]any{"preset": "public_chat"})
// A token from before Bob joined.
before := ts.sync(alice, "").NextBatch
expectStatus(t, ts.post("/_matrix/client/v3/rooms/"+url.PathEscape(roomID)+"/join",
bob.AccessToken, map[string]any{}), http.StatusOK)
membersAt := func(at string) []string {
t.Helper()
path := "/_matrix/client/v3/rooms/" + url.PathEscape(roomID) + "/members"
if at != "" {
path += "?at=" + url.QueryEscape(at)
}
rec := ts.get(path, alice.AccessToken)
expectStatus(t, rec, http.StatusOK)
body := decode[struct {
Chunk []syncEvent `json:"chunk"`
}](t, rec)
out := make([]string, 0, len(body.Chunk))
for _, e := range body.Chunk {
if e.StateKey != nil {
out = append(out, *e.StateKey)
}
}
return out
}
if got := membersAt(""); !contains(got, bob.UserID) {
t.Errorf("current members = %v, want it to include %s", got, bob.UserID)
}
if got := membersAt(before); contains(got, bob.UserID) {
t.Errorf("members at an earlier position = %v, want it to leave out %s", got, bob.UserID)
}
}
func TestMembersRejectsABadAtToken(t *testing.T) {
ts := newTestServer(t, nil)
alice := ts.register("alice", "correct-horse-battery-staple")
roomID := ts.createRoom(alice, nil)
rec := ts.get("/_matrix/client/v3/rooms/"+url.PathEscape(roomID)+"/members?at=nonsense",
alice.AccessToken)
expectError(t, rec, http.StatusBadRequest, "M_INVALID_PARAM")
}