-
Notifications
You must be signed in to change notification settings - Fork 52
/
Copy pathevent.go
1212 lines (1102 loc) · 37 KB
/
event.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
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* Copyright 2016-2017 Vector Creations Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package gomatrixserverlib
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"reflect"
"strings"
"time"
"unsafe"
"github.com/matrix-org/util"
"github.com/tidwall/gjson"
"github.com/tidwall/sjson"
"golang.org/x/crypto/ed25519"
)
// A StateKeyTuple is the combination of an event type and an event state key.
// It is often used as a key in maps.
type StateKeyTuple struct {
// The "type" key of a matrix event.
EventType string
// The "state_key" of a matrix event.
// The empty string is a legitimate value for the "state_key" in matrix
// so take care to initialise this field lest you accidentally request a
// "state_key" with the go default of the empty string.
StateKey string
}
// An EventReference is a reference to a matrix event.
type EventReference struct {
// The event ID of the event.
EventID string
// The sha256 of the redacted event.
EventSHA256 Base64Bytes
}
// Event validation errors
const (
EventValidationTooLarge int = 1
)
// EventValidationError is returned if there is a problem validating an event
type EventValidationError struct {
Message string
Code int
}
func (e EventValidationError) Error() string {
return e.Message
}
// An EventBuilder is used to build a new event.
// These can be exchanged between matrix servers in the federation APIs when
// joining or leaving a room.
type EventBuilder struct {
// The user ID of the user sending the event.
Sender string `json:"sender"`
// The room ID of the room this event is in.
RoomID string `json:"room_id"`
// The type of the event.
Type string `json:"type"`
// The state_key of the event if the event is a state event or nil if the event is not a state event.
StateKey *string `json:"state_key,omitempty"`
// The events that immediately preceded this event in the room history. This can be
// either []EventReference for room v1/v2, and []string for room v3 onwards.
PrevEvents interface{} `json:"prev_events"`
// The events needed to authenticate this event. This can be
// either []EventReference for room v1/v2, and []string for room v3 onwards.
AuthEvents interface{} `json:"auth_events"`
// The event ID of the event being redacted if this event is a "m.room.redaction".
Redacts string `json:"redacts,omitempty"`
// The depth of the event, This should be one greater than the maximum depth of the previous events.
// The create event has a depth of 1.
Depth int64 `json:"depth"`
// The JSON object for "signatures" key of the event.
Signature RawJSON `json:"signatures,omitempty"`
// The JSON object for "content" key of the event.
Content RawJSON `json:"content"`
// The JSON object for the "unsigned" key
Unsigned RawJSON `json:"unsigned,omitempty"`
}
// SetContent sets the JSON content key of the event.
func (eb *EventBuilder) SetContent(content interface{}) (err error) {
eb.Content, err = json.Marshal(content)
return
}
// SetUnsigned sets the JSON unsigned key of the event.
func (eb *EventBuilder) SetUnsigned(unsigned interface{}) (err error) {
eb.Unsigned, err = json.Marshal(unsigned)
return
}
// An Event is a matrix event.
// The event should always contain valid JSON.
// If the event content hash is invalid then the event is redacted.
// Redacted events contain only the fields covered by the event signature.
// The fields have different formats depending on the room version - see
// eventFormatV1Fields, eventFormatV2Fields.
type Event struct {
redacted bool
eventID string
eventJSON []byte
fields interface {
CacheCost() int
}
roomVersion RoomVersion
}
type eventFields struct {
RoomID string `json:"room_id"`
Sender string `json:"sender"`
Type string `json:"type"`
StateKey *string `json:"state_key"`
Content RawJSON `json:"content"`
Redacts string `json:"redacts"`
Depth int64 `json:"depth"`
Unsigned RawJSON `json:"unsigned"`
OriginServerTS Timestamp `json:"origin_server_ts"`
Origin ServerName `json:"origin"`
}
// Fields for room versions 1, 2.
type eventFormatV1Fields struct {
eventFields
EventID string `json:"event_id,omitempty"`
PrevEvents []EventReference `json:"prev_events"`
AuthEvents []EventReference `json:"auth_events"`
}
// Fields for room versions 3, 4, 5.
type eventFormatV2Fields struct {
eventFields
PrevEvents []string `json:"prev_events"`
AuthEvents []string `json:"auth_events"`
}
func (e *Event) CacheCost() int {
return int(unsafe.Sizeof(*e)) +
len(e.eventID) +
(cap(e.eventJSON) * 2) +
len(e.roomVersion) +
1 + // redacted bool
e.fields.CacheCost()
}
func (e *eventFields) CacheCost() int {
cost := int(unsafe.Sizeof(*e)) +
len(e.RoomID) +
len(e.Sender) +
len(e.Type) +
cap(e.Content) +
len(e.Redacts) +
4 + // depth int64
cap(e.Unsigned) +
4 + // originserverts timestamp as uint64
len(e.Origin)
if e.StateKey != nil {
cost += len(*e.StateKey)
}
return cost
}
func (e eventFormatV1Fields) CacheCost() int {
cost := e.eventFields.CacheCost() +
int(unsafe.Sizeof(e)) +
len(e.EventID)
for _, v := range e.PrevEvents {
cost += len(v.EventID) + cap(v.EventSHA256)
}
for _, v := range e.AuthEvents {
cost += len(v.EventID) + cap(v.EventSHA256)
}
return cost
}
func (e eventFormatV2Fields) CacheCost() int {
cost := e.eventFields.CacheCost() +
int(unsafe.Sizeof(e))
for _, v := range e.PrevEvents {
cost += len(v)
}
for _, v := range e.AuthEvents {
cost += len(v)
}
return cost
}
var emptyEventReferenceList = []EventReference{}
// Build a new Event.
// This is used when a local event is created on this server.
// Call this after filling out the necessary fields.
// This can be called multiple times on the same builder.
// A different event ID must be supplied each time this is called.
func (eb *EventBuilder) Build(
now time.Time, origin ServerName, keyID KeyID,
privateKey ed25519.PrivateKey, roomVersion RoomVersion,
) (result *Event, err error) {
if ver, ok := SupportedRoomVersions()[roomVersion]; !ok || !ver.Supported {
return nil, UnsupportedRoomVersionError{
Version: roomVersion,
}
}
eventFormat, err := roomVersion.EventFormat()
if err != nil {
return result, err
}
eventIDFormat, err := roomVersion.EventIDFormat()
if err != nil {
return result, err
}
var event struct {
EventBuilder
EventID string `json:"event_id"`
OriginServerTS Timestamp `json:"origin_server_ts"`
Origin ServerName `json:"origin"`
// This key is either absent or an empty list.
// If it is absent then the pointer is nil and omitempty removes it.
// Otherwise it points to an empty list and omitempty keeps it.
PrevState *[]EventReference `json:"prev_state,omitempty"`
}
event.EventBuilder = *eb
if eventIDFormat == EventIDFormatV1 {
event.EventID = fmt.Sprintf("$%s:%s", util.RandomString(16), origin)
}
event.OriginServerTS = AsTimestamp(now)
event.Origin = origin
switch eventFormat {
case EventFormatV1:
// If either prev_events or auth_events are nil slices then Go will
// marshal them into 'null' instead of '[]', which is bad. Since the
// EventBuilder struct is instantiated outside of gomatrixserverlib
// let's just make sure that they haven't been left as nil slices.
if event.PrevEvents == nil {
event.PrevEvents = []EventReference{}
}
if event.AuthEvents == nil {
event.AuthEvents = []EventReference{}
}
case EventFormatV2:
// In this event format, prev_events and auth_events are lists of
// event IDs as a []string, rather than full-blown []EventReference.
// Since gomatrixserverlib otherwise deals with EventReferences,
// take the event IDs out of these and replace the prev_events and
// auth_events with those new arrays.
switch prevEvents := event.PrevEvents.(type) {
case []string:
event.PrevEvents = prevEvents
case []EventReference:
resPrevEvents := []string{}
for _, prevEvent := range prevEvents {
resPrevEvents = append(resPrevEvents, prevEvent.EventID)
}
event.PrevEvents = resPrevEvents
case nil:
event.PrevEvents = []string{}
}
switch authEvents := event.AuthEvents.(type) {
case []string:
event.AuthEvents = authEvents
case []EventReference:
resAuthEvents := []string{}
for _, authEvent := range authEvents {
resAuthEvents = append(resAuthEvents, authEvent.EventID)
}
event.AuthEvents = resAuthEvents
case nil:
event.AuthEvents = []string{}
}
}
if event.StateKey != nil {
// In early versions of the matrix protocol state events
// had a "prev_state" key that listed the state events with
// the same type and state key that this event replaced.
// This was later dropped from the protocol.
// Synapse ignores the contents of the key but still expects
// the key to be present in state events.
event.PrevState = &emptyEventReferenceList
}
var eventJSON []byte
if eventJSON, err = json.Marshal(&event); err != nil {
return
}
if eventFormat == EventFormatV2 {
if eventJSON, err = sjson.DeleteBytes(eventJSON, "event_id"); err != nil {
return
}
}
if eventJSON, err = addContentHashesToEvent(eventJSON); err != nil {
return
}
if eventJSON, err = signEvent(string(origin), keyID, privateKey, eventJSON, roomVersion); err != nil {
return
}
if eventJSON, err = EnforcedCanonicalJSON(eventJSON, roomVersion); err != nil {
return
}
result = &Event{}
result.roomVersion = roomVersion
if err = result.populateFieldsFromJSON("", eventJSON); err != nil {
return
}
if err = result.CheckFields(); err != nil {
return
}
return
}
// NewEventFromUntrustedJSON loads a new event from some JSON that may be invalid.
// This checks that the event is valid JSON.
// It also checks the content hashes to ensure the event has not been tampered with.
// This should be used when receiving new events from remote servers.
func NewEventFromUntrustedJSON(eventJSON []byte, roomVersion RoomVersion) (result *Event, err error) {
if ver, ok := SupportedRoomVersions()[roomVersion]; !ok || !ver.Supported {
return nil, UnsupportedRoomVersionError{
Version: roomVersion,
}
}
if r := gjson.GetBytes(eventJSON, "_*"); r.Exists() {
err = fmt.Errorf("gomatrixserverlib NewEventFromUntrustedJSON: %w", UnexpectedHeaderedEvent{})
return
}
var enforceCanonicalJSON bool
if enforceCanonicalJSON, err = roomVersion.EnforceCanonicalJSON(); err != nil {
return
}
if enforceCanonicalJSON {
if err = verifyEnforcedCanonicalJSON(eventJSON); err != nil {
err = BadJSONError{err}
return
}
}
result = &Event{}
result.roomVersion = roomVersion
var eventFormat EventFormat
eventFormat, err = result.roomVersion.EventFormat()
if err != nil {
return
}
if eventJSON, err = sjson.DeleteBytes(eventJSON, "unsigned"); err != nil {
return
}
if eventFormat == EventFormatV2 {
if eventJSON, err = sjson.DeleteBytes(eventJSON, "event_id"); err != nil {
return
}
}
if err = result.populateFieldsFromJSON("", eventJSON); err != nil {
return
}
// 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"} {
if eventJSON, err = sjson.DeleteBytes(eventJSON, key); err != nil {
return
}
}
// We know the JSON must be valid here.
eventJSON = CanonicalJSONAssumeValid(eventJSON)
if err = checkEventContentHash(eventJSON); err != nil {
result.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 = RedactEventJSON(eventJSON, roomVersion); err != nil {
return
}
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) {
if result, err = NewEventFromTrustedJSON(redactedJSON, true, roomVersion); err != nil {
return
}
}
}
err = result.CheckFields()
return
}
// NewEventFromTrustedJSON loads a new event from some JSON that must be valid.
// This will be more efficient than NewEventFromUntrustedJSON since it can skip cryptographic checks.
// This can be used when loading matrix events from a local database.
func NewEventFromTrustedJSON(eventJSON []byte, redacted bool, roomVersion RoomVersion) (result *Event, err error) {
if ver, ok := SupportedRoomVersions()[roomVersion]; !ok || !ver.Supported {
return nil, UnsupportedRoomVersionError{
Version: roomVersion,
}
}
result = &Event{}
result.roomVersion = roomVersion
result.redacted = redacted
err = result.populateFieldsFromJSON("", eventJSON) // "" -> event ID not known
return
}
// NewEventFromTrustedJSONWithEventID loads a new event from some JSON that must be valid
// and that the event ID is already known. This must ONLY be used when retrieving
// an event from the database and NEVER when accepting an event over federation.
// This will be more efficient than NewEventFromTrustedJSON since, if the event
// ID is known, we skip all the reference hash and canonicalisation work.
func NewEventFromTrustedJSONWithEventID(eventID string, eventJSON []byte, redacted bool, roomVersion RoomVersion) (result *Event, err error) {
if ver, ok := SupportedRoomVersions()[roomVersion]; !ok || !ver.Supported {
return nil, UnsupportedRoomVersionError{
Version: roomVersion,
}
}
result = &Event{}
result.roomVersion = roomVersion
result.redacted = redacted
err = result.populateFieldsFromJSON(eventID, eventJSON)
return
}
// populateFieldsFromJSON takes the JSON and populates the event
// fields with it. If the event ID is already known, because the
// event came from storage, then we pass it in here as a means of
// avoiding all of the canonicalisation and reference hash
// calculations etc as they are expensive operations. If the event
// ID isn't known, pass an empty string and we'll work it out.
func (e *Event) populateFieldsFromJSON(eventIDIfKnown string, eventJSON []byte) error {
// Work out the format of the event from the room version.
var eventFormat EventFormat
eventFormat, err := e.roomVersion.EventFormat()
if err != nil {
return err
}
switch eventFormat {
case EventFormatV1:
e.eventJSON = eventJSON
// Unmarshal the event fields.
fields := eventFormatV1Fields{}
if err := json.Unmarshal(eventJSON, &fields); err != nil {
return err
}
// Populate the fields of the received object.
fields.fixNilSlices()
e.fields = fields
// In room versions 1 and 2, we will use the event_id from the
// event itself.
e.eventID = fields.EventID
case EventFormatV2:
e.eventJSON = eventJSON
// Unmarshal the event fields.
fields := eventFormatV2Fields{}
if err := json.Unmarshal(eventJSON, &fields); err != nil {
return err
}
// Generate a hash of the event which forms the event ID. There
// is no event_id field in room versions 3 and later so we will
// always generate our own.
if eventIDIfKnown != "" {
e.eventID = eventIDIfKnown
} else if e.eventID, err = e.generateEventID(); err != nil {
return err
}
// Populate the fields of the received object.
fields.fixNilSlices()
e.fields = fields
default:
return errors.New("gomatrixserverlib: room version not supported")
}
return nil
}
// Redacted returns whether the event is redacted.
func (e *Event) Redacted() bool { return e.redacted }
// Version returns the version of this event
func (e *Event) Version() RoomVersion { return e.roomVersion }
// JSON returns the JSON bytes for the event.
func (e *Event) JSON() []byte { return e.eventJSON }
// Redact redacts the event.
func (e *Event) Redact() {
if e.redacted {
return
}
eventJSON, err := RedactEventJSON(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", 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))
}
if err = e.populateFieldsFromJSON(e.EventID(), eventJSON); err != nil {
panic(fmt.Errorf("gomatrixserverlib: populateFieldsFromJSON failed %v", err))
}
e.redacted = true
}
// SetUnsigned sets the unsigned key of the event.
// Returns a copy of the event with the "unsigned" key set.
func (e *Event) SetUnsigned(unsigned interface{}) (*Event, error) {
var eventAsMap map[string]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
}
if err = e.updateUnsignedFields(unsignedJSON); err != nil {
return nil, err
}
result := *e
result.eventJSON = eventJSON
return &result, nil
}
// SetUnsignedField takes a path and value to insert into the unsigned dict of
// the event.
// path is a dot separated path into the unsigned dict (see gjson package
// for details on format). In particular some characters like '.' and '*' must
// be escaped.
func (e *Event) SetUnsignedField(path string, value interface{}) error {
// The safest way is to change the unsigned json and then reparse the
// event fully. But since we are only changing the unsigned section,
// which doesn't affect the signatures or hashes, we can cheat and
// just fiddle those bits directly.
path = "unsigned." + path
eventJSON, err := sjson.SetBytes(e.eventJSON, path, value)
if err != nil {
return err
}
eventJSON = CanonicalJSONAssumeValid(eventJSON)
res := gjson.GetBytes(eventJSON, "unsigned")
unsigned := RawJSONFromResult(res, eventJSON)
if err = e.updateUnsignedFields(unsigned); err != nil {
return err
}
e.eventJSON = eventJSON
return nil
}
// updateUnsignedFields sets the value of the unsigned field and then
// fixes nil slices if needed.
func (e *Event) updateUnsignedFields(unsigned []byte) error {
switch fields := e.fields.(type) {
case eventFormatV1Fields:
fields.Unsigned = unsigned
fields.fixNilSlices()
e.fields = fields
case eventFormatV2Fields:
fields.Unsigned = unsigned
fields.fixNilSlices()
e.fields = fields
default:
return UnsupportedRoomVersionError{Version: e.roomVersion}
}
return nil
}
// EventReference returns an EventReference for the event.
// The reference can be used to refer to this event from other events.
func (e *Event) EventReference() EventReference {
reference, err := referenceOfEvent(e.eventJSON, e.roomVersion)
if err != nil {
// This is unreachable for events created with EventBuilder.Build or NewEventFromUntrustedJSON
// This can be reached if NewEventFromTrustedJSON is given JSON from an untrusted source.
panic(fmt.Errorf("gomatrixserverlib: invalid event %v (%q)", err, string(e.eventJSON)))
}
return reference
}
// Sign returns a copy of the event with an additional signature.
func (e *Event) Sign(signingName string, keyID KeyID, privateKey ed25519.PrivateKey) Event {
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)))
}
return Event{
redacted: e.redacted,
eventID: e.eventID,
eventJSON: eventJSON,
fields: e.fields,
roomVersion: e.roomVersion,
}
}
// KeyIDs returns a list of key IDs that the named entity has signed the event with.
func (e *Event) KeyIDs(signingName string) []KeyID {
keyIDs, err := ListKeyIDs(signingName, e.eventJSON)
if err != nil {
// This should unreachable for events created with EventBuilder.Build or NewEventFromUntrustedJSON
panic(fmt.Errorf("gomatrixserverlib: invalid event %v", err))
}
return keyIDs
}
// StateKey returns the "state_key" of the event, or the nil if the event is not a state event.
func (e *Event) StateKey() *string {
switch fields := e.fields.(type) {
case eventFormatV1Fields:
return fields.StateKey
case eventFormatV2Fields:
return fields.StateKey
default:
panic(e.invalidFieldType())
}
}
// StateKeyEquals returns true if the event is a state event and the "state_key" matches.
func (e *Event) StateKeyEquals(stateKey string) bool {
var sk *string
switch fields := e.fields.(type) {
case eventFormatV1Fields:
sk = fields.StateKey
case eventFormatV2Fields:
sk = fields.StateKey
default:
panic(e.invalidFieldType())
}
if sk == nil {
return false
}
return *sk == stateKey
}
const (
// The event ID, room ID, sender, event type and state key fields cannot be
// bigger than this.
// https://github.com/matrix-org/synapse/blob/v0.21.0/synapse/event_auth.py#L173-L182
maxIDLength = 255
// The entire event JSON, including signatures cannot be bigger than this.
// https://github.com/matrix-org/synapse/blob/v0.21.0/synapse/event_auth.py#L183-184
maxEventLength = 65536
)
// CheckFields checks that the event fields are valid.
// Returns an error if the IDs have the wrong format or too long.
// Returns an error if the total length of the event JSON is too long.
// Returns an error if the event ID doesn't match the origin of the event.
// https://matrix.org/docs/spec/client_server/r0.2.0.html#size-limits
func (e *Event) CheckFields() error { // nolint: gocyclo
var fields eventFields
switch f := e.fields.(type) {
case eventFormatV1Fields:
if f.AuthEvents == nil || f.PrevEvents == nil {
return errors.New("gomatrixserverlib: auth events and prev events must not be nil")
}
fields = f.eventFields
case eventFormatV2Fields:
if f.AuthEvents == nil || f.PrevEvents == nil {
return errors.New("gomatrixserverlib: auth events and prev events must not be nil")
}
fields = f.eventFields
default:
panic(e.invalidFieldType())
}
if l := len(e.eventJSON); l > maxEventLength {
return EventValidationError{
Code: EventValidationTooLarge,
Message: fmt.Sprintf("gomatrixserverlib: event is too long, length %d bytes > maximum %d bytes", l, maxEventLength),
}
}
if l := len([]rune(fields.Type)); l > maxIDLength {
return EventValidationError{
Code: EventValidationTooLarge,
Message: fmt.Sprintf("gomatrixserverlib: event type is too long, length %d codepoints > maximum %d codepoints", l, maxIDLength),
}
}
if fields.StateKey != nil {
if l := len([]rune(*fields.StateKey)); l > maxIDLength {
return EventValidationError{
Code: EventValidationTooLarge,
Message: fmt.Sprintf("gomatrixserverlib: state key is too long, length %d codepoints > maximum %d codepoints", l, maxIDLength),
}
}
}
if _, err := checkID(fields.RoomID, "room", '!'); err != nil {
return err
}
origin := fields.Origin
senderDomain, err := checkID(fields.Sender, "user", '@')
if err != nil {
return err
}
if origin != ServerName(senderDomain) {
// For the most part all events should be sent by a user on the
// originating server.
//
// However "m.room.member" events created from third-party invites
// are allowed to have a different sender because they have the same
// sender as the "m.room.third_party_invite" event they derived from.
// https://github.com/matrix-org/synapse/blob/v0.21.0/synapse/event_auth.py#L58-L64
//
// Also, some old versions of synapse had a bug wherein some
// joins/leaves used the origin and event id supplied by the helping
// server instead of the joining/leaving server.
//
// So in general we allow the sender to be different from the
// origin for m.room.member events. In any case, we check it was
// signed by both servers later.
if fields.Type != MRoomMember {
return fmt.Errorf(
"gomatrixserverlib: sender domain doesn't match origin: %q != %q",
senderDomain, origin,
)
}
}
return nil
}
func checkID(id, kind string, sigil byte) (domain string, err error) {
domain, err = domainFromID(id)
if err != nil {
return
}
if id[0] != sigil {
err = fmt.Errorf(
"gomatrixserverlib: invalid %s ID, wanted first byte to be '%c' got '%c'",
kind, sigil, id[0],
)
return
}
if l := len([]rune(id)); l > maxIDLength {
err = EventValidationError{
Code: EventValidationTooLarge,
Message: fmt.Sprintf("gomatrixserverlib: %s ID is too long, length %d codepoints > maximum %d codepoints", kind, l, maxIDLength),
}
return
}
return
}
// Origin returns the name of the server that sent the event
func (e *Event) Origin() ServerName {
switch fields := e.fields.(type) {
case eventFormatV1Fields:
return fields.Origin
case eventFormatV2Fields:
return fields.Origin
default:
panic(e.invalidFieldType())
}
}
func (e *Event) generateEventID() (eventID string, err error) {
var eventFormat EventFormat
eventFormat, err = e.roomVersion.EventFormat()
if err != nil {
return
}
switch eventFormat {
case EventFormatV1:
eventID = e.fields.(eventFormatV1Fields).EventID
case EventFormatV2:
var reference EventReference
reference, err = referenceOfEvent(e.eventJSON, e.roomVersion)
if err != nil {
return
}
eventID = reference.EventID
default:
err = errors.New("gomatrixserverlib: unknown room version")
}
return
}
// EventID returns the event ID of the event.
func (e *Event) EventID() string {
switch fields := e.fields.(type) {
case eventFormatV1Fields:
return fields.EventID
case eventFormatV2Fields:
return e.eventID
default:
panic(e.invalidFieldType())
}
}
// Sender returns the user ID of the sender of the event.
func (e *Event) Sender() string {
switch fields := e.fields.(type) {
case eventFormatV1Fields:
return fields.Sender
case eventFormatV2Fields:
return fields.Sender
default:
panic(e.invalidFieldType())
}
}
// Type returns the type of the event.
func (e *Event) Type() string {
switch fields := e.fields.(type) {
case eventFormatV1Fields:
return fields.Type
case eventFormatV2Fields:
return fields.Type
default:
panic(e.invalidFieldType())
}
}
// OriginServerTS returns the unix timestamp when this event was created on the origin server, with millisecond resolution.
func (e *Event) OriginServerTS() Timestamp {
switch fields := e.fields.(type) {
case eventFormatV1Fields:
return fields.OriginServerTS
case eventFormatV2Fields:
return fields.OriginServerTS
default:
panic(e.invalidFieldType())
}
}
// Unsigned returns the object under the 'unsigned' key of the event.
func (e *Event) Unsigned() []byte {
switch fields := e.fields.(type) {
case eventFormatV1Fields:
return fields.Unsigned
case eventFormatV2Fields:
return fields.Unsigned
default:
panic(e.invalidFieldType())
}
}
// Content returns the content JSON of the event.
func (e *Event) Content() []byte {
switch fields := e.fields.(type) {
case eventFormatV1Fields:
return []byte(fields.Content)
case eventFormatV2Fields:
return []byte(fields.Content)
default:
panic(e.invalidFieldType())
}
}
// PrevEvents returns references to the direct ancestors of the event.
func (e *Event) PrevEvents() []EventReference {
switch fields := e.fields.(type) {
case eventFormatV1Fields:
return fields.PrevEvents
case eventFormatV2Fields:
result := make([]EventReference, 0, len(fields.PrevEvents))
for _, id := range fields.PrevEvents {
// In the new event format, the event ID is already the hash of
// the event. Since we will have generated the event ID before
// now, we can just knock the sigil $ off the front and use that
// as the event SHA256.
var sha Base64Bytes
if err := sha.Decode(id[1:]); err != nil {
panic("gomatrixserverlib: event ID is malformed: " + err.Error())
}
result = append(result, EventReference{
EventID: id,
EventSHA256: sha,
})
}
return result
default:
panic(e.invalidFieldType())
}
}
// PrevEventIDs returns the event IDs of the direct ancestors of the event.
func (e *Event) PrevEventIDs() []string {
switch fields := e.fields.(type) {
case eventFormatV1Fields:
result := make([]string, 0, len(fields.PrevEvents))
for _, id := range fields.PrevEvents {
result = append(result, id.EventID)
}
return result
case eventFormatV2Fields:
return fields.PrevEvents
default:
panic(e.invalidFieldType())
}
}
func (e *Event) extractContent(eventType string, content interface{}) error {
eventFormat, err := e.roomVersion.EventFormat()
if err != nil {
panic(err)
}
var fields eventFields
switch eventFormat {
case EventFormatV1:
fields = e.fields.(eventFormatV1Fields).eventFields
case EventFormatV2:
fields = e.fields.(eventFormatV2Fields).eventFields
default:
panic(e.invalidFieldType())
}
if fields.Type != eventType {
return fmt.Errorf("gomatrixserverlib: not a %s event", eventType)
}
return json.Unmarshal(fields.Content, &content)
}
// Membership returns the value of the content.membership field if this event
// is an "m.room.member" event.
// Returns an error if the event is not a m.room.member event or if the content
// is not valid m.room.member content.
func (e *Event) Membership() (string, error) {
var content struct {
Membership string `json:"membership"`
}
if err := e.extractContent(MRoomMember, &content); err != nil {
return "", err
}
if e.StateKey() == nil {
return "", fmt.Errorf("gomatrixserverlib: Membersip() event is not a m.room.member event, missing state key")
}
return content.Membership, nil
}
// JoinRule returns the value of the content.join_rule field if this event
// is an "m.room.join_rules" event.
// Returns an error if the event is not a m.room.join_rules event or if the content
// is not valid m.room.join_rules content.
func (e *Event) JoinRule() (string, error) {
if !e.StateKeyEquals("") {
return "", fmt.Errorf("gomatrixserverlib: JoinRule() event is not a m.room.join_rules event, bad state key")
}