Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 20 additions & 3 deletions event.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import (
"errors"
"fmt"
"reflect"
"regexp"
"strings"
"time"

Expand Down Expand Up @@ -709,11 +710,27 @@ func (e *Event) CheckFields() error { // nolint: gocyclo
return nil
}

func checkID(id, kind string, sigil byte) (domain string, err error) {
domain, err = domainFromID(id)
if err != nil {
// https://matrix.org/docs/spec/appendices#id12
var validUserIDRegex = regexp.MustCompile(`^[0-9a-z\._=\-/]+$`)

func checkID(id, kind string, sigil byte) (domain ServerName, err error) {
var user string
if user, domain, err = SplitID(sigil, id); err != nil {
err = fmt.Errorf("gomatrixserverlib: invalid ID %q, invalid format: %w", id, err)
return
}
// Check that the characters in the ID are valid for the type
switch sigil {
case '@':
if len(id) > 255 {
err = fmt.Errorf("gomatrixserverlib: invalid ID %q, too long", id)
return
}
if !validUserIDRegex.MatchString(user) {
err = fmt.Errorf("gomatrixserverlib: invalid ID %q, user part %q contains invalid characters", id, user)
return
}
}
if id[0] != sigil {
err = fmt.Errorf(
"gomatrixserverlib: invalid %s ID, wanted first byte to be '%c' got '%c'",
Expand Down
25 changes: 25 additions & 0 deletions event_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -180,3 +180,28 @@ func TestHeaderedEventToNewEventFromUntrustedJSON(t *testing.T) {
t.Fatal("expected an UnexpectedHeaderedEvent error but got:", err)
}
}

func TestValidUserID(t *testing.T) {
userIDsShouldPass := []string{
"@foo:bar.com",
"@foo-baz:bar.com",
"@foo_qux/baz:bar.com",
"@foo.baz:bar.com",
}
userIDsShouldFail := []string{
"@Foo:bar.com",
"@foo%:bar.com",
"@fooé:bar.com",
"@℉oo:bar.com",
}
for _, id := range userIDsShouldPass {
if _, err := checkID(id, "user", '@'); err != nil {
t.Fatalf("%q should have passed but didn't: %s", id, err)
}
}
for _, id := range userIDsShouldFail {
if _, err := checkID(id, "user", '@'); err == nil {
t.Fatalf("%q should have failed but didn't", id)
}
}
}