-
Notifications
You must be signed in to change notification settings - Fork 51
/
eventV2.go
296 lines (257 loc) · 8.65 KB
/
eventV2.go
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
285
286
287
288
289
290
291
292
293
294
295
296
package gomatrixserverlib
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"unicode/utf8"
"github.com/matrix-org/gomatrixserverlib/spec"
"github.com/tidwall/gjson"
"github.com/tidwall/sjson"
"golang.org/x/crypto/ed25519"
)
type eventV2 struct {
eventV1
PrevEvents []string `json:"prev_events"`
AuthEvents []string `json:"auth_events"`
}
func (e *eventV2) PrevEventIDs() []string {
return e.PrevEvents
}
func (e *eventV2) AuthEventIDs() []string {
return e.AuthEvents
}
// MarshalJSON implements json.Marshaller
func (e *eventV2) MarshalJSON() ([]byte, error) {
if e.eventJSON == nil {
return nil, fmt.Errorf("gomatrixserverlib: cannot serialise uninitialised Event")
}
return e.eventJSON, nil
}
func (e *eventV2) SetUnsigned(unsigned interface{}) (PDU, error) {
var eventAsMap map[string]spec.RawJSON
var err error
if err = json.Unmarshal(e.eventJSON, &eventAsMap); err != nil {
return nil, err
}
unsignedJSON, err := json.Marshal(unsigned)
if err != nil {
return nil, err
}
eventAsMap["unsigned"] = unsignedJSON
eventJSON, err := json.Marshal(eventAsMap)
if err != nil {
return nil, err
}
if eventJSON, err = EnforcedCanonicalJSON(eventJSON, e.roomVersion); err != nil {
return nil, err
}
result := *e
result.eventJSON = eventJSON
result.eventFields.Unsigned = unsignedJSON
return &result, nil
}
func (e *eventV2) SenderID() spec.SenderID {
return spec.SenderID(e.eventFields.SenderID)
}
func (e *eventV2) EventID() string {
// if we already generated the eventID, don't do it again
if e.EventIDRaw != "" {
return e.EventIDRaw
}
ref, err := referenceOfEvent(e.eventJSON, e.roomVersion)
if err != nil {
panic(fmt.Errorf("failed to generate reference of event: %w", err))
}
e.EventIDRaw = ref.EventID
return ref.EventID
}
func (e *eventV2) Redact() {
if e.redacted {
return
}
verImpl, err := GetRoomVersion(e.roomVersion)
if err != nil {
panic(fmt.Errorf("gomatrixserverlib: invalid event %v", err))
}
eventJSON, err := verImpl.RedactEventJSON(e.eventJSON)
if err != nil {
// This is unreachable for events created with EventBuilder.Build or NewEventFromUntrustedJSON
panic(fmt.Errorf("gomatrixserverlib: invalid event %v", err))
}
if eventJSON, err = EnforcedCanonicalJSON(eventJSON, e.roomVersion); err != nil {
// This is unreachable for events created with EventBuilder.Build or NewEventFromUntrustedJSON
panic(fmt.Errorf("gomatrixserverlib: invalid event %v", err))
}
var res eventV2
err = json.Unmarshal(eventJSON, &res)
if err != nil {
panic(fmt.Errorf("gomatrixserverlib: Redact failed %v", err))
}
res.redacted = true
res.eventJSON = eventJSON
res.roomVersion = e.roomVersion
*e = res
}
func (e *eventV2) Sign(signingName string, keyID KeyID, privateKey ed25519.PrivateKey) PDU {
eventJSON, err := signEvent(signingName, keyID, privateKey, e.eventJSON, e.roomVersion)
if err != nil {
// This is unreachable for events created with EventBuilder.Build or NewEventFromUntrustedJSON
panic(fmt.Errorf("gomatrixserverlib: invalid event %v (%q)", err, string(e.eventJSON)))
}
if eventJSON, err = EnforcedCanonicalJSON(eventJSON, e.roomVersion); err != nil {
// This is unreachable for events created with EventBuilder.Build or NewEventFromUntrustedJSON
panic(fmt.Errorf("gomatrixserverlib: invalid event %v (%q)", err, string(e.eventJSON)))
}
res := &e
(*res).eventJSON = eventJSON
return *res
}
func newEventFromUntrustedJSONV2(eventJSON []byte, roomVersion IRoomVersion) (PDU, error) {
if r := gjson.GetBytes(eventJSON, "_*"); r.Exists() {
return nil, fmt.Errorf("gomatrixserverlib NewEventFromUntrustedJSON: found top-level '_' key, is this a headered event: %v", string(eventJSON))
}
if err := roomVersion.CheckCanonicalJSON(eventJSON); err != nil {
return nil, BadJSONError{err}
}
res := &eventV2{}
var err error
// Synapse removes these keys from events in case a server accidentally added them.
// https://github.com/matrix-org/synapse/blob/v0.18.5/synapse/crypto/event_signing.py#L57-L62
for _, key := range []string{"outlier", "destinations", "age_ts", "unsigned", "event_id"} {
if eventJSON, err = sjson.DeleteBytes(eventJSON, key); err != nil {
return nil, err
}
}
if err = json.Unmarshal(eventJSON, &res); err != nil {
return nil, err
}
if err := checkID(res.eventFields.RoomID, "room", '!'); err != nil {
return nil, err
}
res.roomVersion = roomVersion.Version()
// We know the JSON must be valid here.
eventJSON = CanonicalJSONAssumeValid(eventJSON)
res.eventJSON = eventJSON
if err = checkEventContentHash(eventJSON); err != nil {
res.redacted = true
// If the content hash doesn't match then we have to discard all non-essential fields
// because they've been tampered with.
var redactedJSON []byte
if redactedJSON, err = roomVersion.RedactEventJSON(eventJSON); err != nil {
return nil, err
}
redactedJSON = CanonicalJSONAssumeValid(redactedJSON)
// We need to ensure that `result` is the redacted event.
// If redactedJSON is the same as eventJSON then `result` is already
// correct. If not then we need to reparse.
//
// Yes, this means that for some events we parse twice (which is slow),
// but means that parsing unredacted events is fast.
if !bytes.Equal(redactedJSON, eventJSON) {
result, err := roomVersion.NewEventFromTrustedJSON(redactedJSON, true)
if err != nil {
return nil, err
}
err = CheckFields(result)
return result, err
}
}
err = CheckFields(res)
return res, err
}
var lenientByteLimitRoomVersions = map[RoomVersion]struct{}{
RoomVersionV1: {},
RoomVersionV2: {},
RoomVersionV3: {},
RoomVersionV4: {},
RoomVersionV5: {},
RoomVersionV6: {},
RoomVersionV7: {},
RoomVersionV8: {},
RoomVersionV9: {},
RoomVersionV10: {},
RoomVersionV11: {},
RoomVersionPseudoIDs: {},
"org.matrix.msc3787": {},
"org.matrix.msc3667": {},
}
func CheckFields(input PDU) error { // nolint: gocyclo
if input.AuthEventIDs() == nil || input.PrevEventIDs() == nil {
return errors.New("gomatrixserverlib: auth events and prev events must not be nil")
}
if l := len(input.JSON()); l > maxEventLength {
return EventValidationError{
Code: EventValidationTooLarge,
Message: fmt.Sprintf("gomatrixserverlib: event is too long, length %d bytes > maximum %d bytes", l, maxEventLength),
}
}
// Compatibility to Synapse and older rooms. This was always enforced by Synapse
if l := utf8.RuneCountInString(input.Type()); l > maxIDLength {
return EventValidationError{
Code: EventValidationTooLarge,
Message: fmt.Sprintf("gomatrixserverlib: event type is too long, length %d bytes > maximum %d bytes", l, maxIDLength),
}
}
if input.StateKey() != nil {
if l := utf8.RuneCountInString(*input.StateKey()); l > maxIDLength {
return EventValidationError{
Code: EventValidationTooLarge,
Message: fmt.Sprintf("gomatrixserverlib: state key is too long, length %d bytes > maximum %d bytes", l, maxIDLength),
}
}
}
_, persistable := lenientByteLimitRoomVersions[input.Version()]
// Byte size check: if these fail, then be lenient to avoid breaking rooms.
if l := len(input.Type()); l > maxIDLength {
return EventValidationError{
Code: EventValidationTooLarge,
Message: fmt.Sprintf("gomatrixserverlib: event type is too long, length %d bytes > maximum %d bytes", l, maxIDLength),
Persistable: persistable,
}
}
if input.StateKey() != nil {
if l := len(*input.StateKey()); l > maxIDLength {
return EventValidationError{
Code: EventValidationTooLarge,
Message: fmt.Sprintf("gomatrixserverlib: state key is too long, length %d bytes > maximum %d bytes", l, maxIDLength),
Persistable: persistable,
}
}
}
switch input.Version() {
case RoomVersionPseudoIDs:
default:
if err := checkID(string(input.SenderID()), "user", '@'); err != nil {
return err
}
}
return nil
}
func newEventFromTrustedJSONV2(eventJSON []byte, redacted bool, roomVersion IRoomVersion) (PDU, error) {
res := eventV2{}
if err := json.Unmarshal(eventJSON, &res); err != nil {
return nil, err
}
if err := checkID(res.eventFields.RoomID, "room", '!'); err != nil {
return nil, err
}
res.roomVersion = roomVersion.Version()
res.redacted = redacted
res.eventJSON = eventJSON
return &res, nil
}
func newEventFromTrustedJSONWithEventIDV2(eventID string, eventJSON []byte, redacted bool, roomVersion IRoomVersion) (PDU, error) {
res := &eventV2{}
if err := json.Unmarshal(eventJSON, &res); err != nil {
return nil, err
}
if err := checkID(res.eventFields.RoomID, "room", '!'); err != nil {
return nil, err
}
res.roomVersion = roomVersion.Version()
res.eventJSON = eventJSON
res.EventIDRaw = eventID
res.redacted = redacted
return res, nil
}