aboutsummaryrefslogtreecommitdiff
path: root/test/room.go
blob: 140c100ede41535ce43b30aa9b8b112ce79088c5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
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
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
// Copyright 2022 The Matrix.org Foundation C.I.C.
//
// 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 test

import (
	"encoding/json"
	"fmt"
	"sync/atomic"
	"testing"
	"time"

	"github.com/matrix-org/gomatrixserverlib"
	"github.com/matrix-org/gomatrixserverlib/spec"

	"github.com/matrix-org/dendrite/internal/eventutil"
	rstypes "github.com/matrix-org/dendrite/roomserver/types"
)

type Preset int

var (
	PresetNone               Preset = 0
	PresetPrivateChat        Preset = 1
	PresetPublicChat         Preset = 2
	PresetTrustedPrivateChat Preset = 3

	roomIDCounter = int64(0)
)

type Room struct {
	ID           string
	Version      gomatrixserverlib.RoomVersion
	preset       Preset
	guestCanJoin bool
	visibility   gomatrixserverlib.HistoryVisibility
	creator      *User

	authEvents   gomatrixserverlib.AuthEvents
	currentState map[string]*rstypes.HeaderedEvent
	events       []*rstypes.HeaderedEvent
}

// Create a new test room. Automatically creates the initial create events.
func NewRoom(t *testing.T, creator *User, modifiers ...roomModifier) *Room {
	t.Helper()
	counter := atomic.AddInt64(&roomIDCounter, 1)
	if creator.srvName == "" {
		t.Fatalf("NewRoom: creator doesn't belong to a server: %+v", *creator)
	}
	r := &Room{
		ID:           fmt.Sprintf("!%d:%s", counter, creator.srvName),
		creator:      creator,
		authEvents:   gomatrixserverlib.NewAuthEvents(nil),
		preset:       PresetPublicChat,
		Version:      gomatrixserverlib.RoomVersionV9,
		currentState: make(map[string]*rstypes.HeaderedEvent),
		visibility:   gomatrixserverlib.HistoryVisibilityShared,
	}
	for _, m := range modifiers {
		m(t, r)
	}
	r.insertCreateEvents(t)
	return r
}

func (r *Room) MustGetAuthEventRefsForEvent(t *testing.T, needed gomatrixserverlib.StateNeeded) []gomatrixserverlib.EventReference {
	t.Helper()
	a, err := needed.AuthEventReferences(&r.authEvents)
	if err != nil {
		t.Fatalf("MustGetAuthEvents: %v", err)
	}
	return a
}

func (r *Room) ForwardExtremities() []string {
	if len(r.events) == 0 {
		return nil
	}
	return []string{
		r.events[len(r.events)-1].EventID(),
	}
}

func (r *Room) insertCreateEvents(t *testing.T) {
	t.Helper()
	var joinRule gomatrixserverlib.JoinRuleContent
	var hisVis gomatrixserverlib.HistoryVisibilityContent
	plContent := eventutil.InitialPowerLevelsContent(r.creator.ID)
	switch r.preset {
	case PresetTrustedPrivateChat:
		fallthrough
	case PresetPrivateChat:
		joinRule.JoinRule = "invite"
		hisVis.HistoryVisibility = gomatrixserverlib.HistoryVisibilityShared
	case PresetPublicChat:
		joinRule.JoinRule = "public"
		hisVis.HistoryVisibility = gomatrixserverlib.HistoryVisibilityShared
	}

	if r.visibility != "" {
		hisVis.HistoryVisibility = r.visibility
	}

	r.CreateAndInsert(t, r.creator, spec.MRoomCreate, map[string]interface{}{
		"creator":      r.creator.ID,
		"room_version": r.Version,
	}, WithStateKey(""))
	r.CreateAndInsert(t, r.creator, spec.MRoomMember, map[string]interface{}{
		"membership": "join",
	}, WithStateKey(r.creator.ID))
	r.CreateAndInsert(t, r.creator, spec.MRoomPowerLevels, plContent, WithStateKey(""))
	r.CreateAndInsert(t, r.creator, spec.MRoomJoinRules, joinRule, WithStateKey(""))
	r.CreateAndInsert(t, r.creator, spec.MRoomHistoryVisibility, hisVis, WithStateKey(""))
	if r.guestCanJoin {
		r.CreateAndInsert(t, r.creator, spec.MRoomGuestAccess, map[string]string{
			"guest_access": "can_join",
		}, WithStateKey(""))
	}
}

// Create an event in this room but do not insert it. Does not modify the room in any way (depth, fwd extremities, etc) so is thread-safe.
func (r *Room) CreateEvent(t *testing.T, creator *User, eventType string, content interface{}, mods ...eventModifier) *rstypes.HeaderedEvent {
	t.Helper()
	depth := 1 + len(r.events) // depth starts at 1

	// possible event modifiers (optional fields)
	mod := &eventMods{}
	for _, m := range mods {
		m(mod)
	}

	if mod.privKey == nil {
		mod.privKey = creator.privKey
	}
	if mod.keyID == "" {
		mod.keyID = creator.keyID
	}
	if mod.originServerTS.IsZero() {
		mod.originServerTS = time.Now()
	}
	if mod.origin == "" {
		mod.origin = creator.srvName
	}

	var unsigned spec.RawJSON
	var err error
	if mod.unsigned != nil {
		unsigned, err = json.Marshal(mod.unsigned)
		if err != nil {
			t.Fatalf("CreateEvent[%s]: failed to marshal unsigned field: %s", eventType, err)
		}
	}

	builder := &gomatrixserverlib.EventBuilder{
		Sender:   creator.ID,
		RoomID:   r.ID,
		Type:     eventType,
		StateKey: mod.stateKey,
		Depth:    int64(depth),
		Unsigned: unsigned,
	}
	err = builder.SetContent(content)
	if err != nil {
		t.Fatalf("CreateEvent[%s]: failed to SetContent: %s", eventType, err)
	}
	if depth > 1 {
		builder.PrevEvents = []gomatrixserverlib.EventReference{r.events[len(r.events)-1].EventReference()}
	}

	eventsNeeded, err := gomatrixserverlib.StateNeededForEventBuilder(builder)
	if err != nil {
		t.Fatalf("CreateEvent[%s]: failed to StateNeededForEventBuilder: %s", eventType, err)
	}

	refs, err := eventsNeeded.AuthEventReferences(&r.authEvents)
	if err != nil {
		t.Fatalf("CreateEvent[%s]: failed to AuthEventReferences: %s", eventType, err)
	}
	builder.AuthEvents = refs

	if len(mod.authEvents) > 0 {
		builder.AuthEvents = mod.authEvents
	}

	ev, err := builder.Build(
		mod.originServerTS, mod.origin, mod.keyID,
		mod.privKey, r.Version,
	)
	if err != nil {
		t.Fatalf("CreateEvent[%s]: failed to build event: %s", eventType, err)
	}
	if err = gomatrixserverlib.Allowed(ev, &r.authEvents); err != nil {
		t.Fatalf("CreateEvent[%s]: failed to verify event was allowed: %s", eventType, err)
	}
	headeredEvent := &rstypes.HeaderedEvent{Event: ev}
	headeredEvent.Visibility = r.visibility
	return headeredEvent
}

// Add a new event to this room DAG. Not thread-safe.
func (r *Room) InsertEvent(t *testing.T, he *rstypes.HeaderedEvent) {
	t.Helper()
	// Add the event to the list of auth/state events
	r.events = append(r.events, he)
	if he.StateKey() != nil {
		err := r.authEvents.AddEvent(he.Event)
		if err != nil {
			t.Fatalf("InsertEvent: failed to add event to auth events: %s", err)
		}
		r.currentState[he.Type()+" "+*he.StateKey()] = he
	}
}

func (r *Room) Events() []*rstypes.HeaderedEvent {
	return r.events
}

func (r *Room) CurrentState() []*rstypes.HeaderedEvent {
	events := make([]*rstypes.HeaderedEvent, len(r.currentState))
	i := 0
	for _, e := range r.currentState {
		events[i] = e
		i++
	}
	return events
}

func (r *Room) CreateAndInsert(t *testing.T, creator *User, eventType string, content interface{}, mods ...eventModifier) *rstypes.HeaderedEvent {
	t.Helper()
	he := r.CreateEvent(t, creator, eventType, content, mods...)
	r.InsertEvent(t, he)
	return he
}

// All room modifiers are below

type roomModifier func(t *testing.T, r *Room)

func RoomPreset(p Preset) roomModifier {
	return func(t *testing.T, r *Room) {
		switch p {
		case PresetPrivateChat:
			fallthrough
		case PresetPublicChat:
			fallthrough
		case PresetTrustedPrivateChat:
			fallthrough
		case PresetNone:
			r.preset = p
		default:
			t.Errorf("invalid RoomPreset: %v", p)
		}
	}
}

func RoomHistoryVisibility(vis gomatrixserverlib.HistoryVisibility) roomModifier {
	return func(t *testing.T, r *Room) {
		r.visibility = vis
	}
}

func RoomVersion(ver gomatrixserverlib.RoomVersion) roomModifier {
	return func(t *testing.T, r *Room) {
		r.Version = ver
	}
}

func GuestsCanJoin(canJoin bool) roomModifier {
	return func(t *testing.T, r *Room) {
		r.guestCanJoin = canJoin
	}
}