| 1 |
// Copyright (c) 2021 Tulir Asokan |
| 2 |
// |
| 3 |
// This Source Code Form is subject to the terms of the Mozilla Public |
| 4 |
// License, v. 2.0. If a copy of the MPL was not distributed with this |
| 5 |
// file, You can obtain one at http://mozilla.org/MPL/2.0/. |
| 6 |
|
| 7 |
package id |
| 8 |
|
| 9 |
import ( |
| 10 |
"bytes" |
| 11 |
"encoding/hex" |
| 12 |
"errors" |
| 13 |
"fmt" |
| 14 |
"regexp" |
| 15 |
"strings" |
| 16 |
) |
| 17 |
|
| 18 |
// UserID represents a Matrix user ID. |
| 19 |
// https://matrix.org/docs/spec/appendices#user-identifiers |
| 20 |
type UserID string |
| 21 |
|
| 22 |
const UserIDMaxLength = 255 |
| 23 |
|
| 24 |
func NewUserID(localpart, homeserver string) UserID { |
| 25 |
return UserID(fmt.Sprintf("@%s:%s", localpart, homeserver)) |
| 26 |
} |
| 27 |
|
| 28 |
func NewEncodedUserID(localpart, homeserver string) UserID { |
| 29 |
return NewUserID(EncodeUserLocalpart(localpart), homeserver) |
| 30 |
} |
| 31 |
|
| 32 |
var ( |
| 33 |
ErrInvalidUserID = errors.New("is not a valid user ID") |
| 34 |
ErrNoncompliantLocalpart = errors.New("contains characters that are not allowed") |
| 35 |
ErrUserIDTooLong = errors.New("the given user ID is longer than 255 characters") |
| 36 |
ErrEmptyLocalpart = errors.New("empty localparts are not allowed") |
| 37 |
) |
| 38 |
|
| 39 |
// Parse parses the user ID into the localpart and server name. |
| 40 |
// |
| 41 |
// Note that this only enforces very basic user ID formatting requirements: user IDs start with |
| 42 |
// a @, and contain a : after the @. If you want to enforce localpart validity, see the |
| 43 |
// ParseAndValidate and ValidateUserLocalpart functions. |
| 44 |
func (userID UserID) Parse() (localpart, homeserver string, err error) { |
| 45 |
if len(userID) == 0 || userID[0] != '@' || !strings.ContainsRune(string(userID), ':') { |
| 46 |
// This error wrapping lets you use errors.Is() nicely even though the message contains the user ID |
| 47 |
err = fmt.Errorf("'%s' %w", userID, ErrInvalidUserID) |
| 48 |
return |
| 49 |
} |
| 50 |
parts := strings.SplitN(string(userID), ":", 2) |
| 51 |
localpart, homeserver = strings.TrimPrefix(parts[0], "@"), parts[1] |
| 52 |
return |
| 53 |
} |
| 54 |
|
| 55 |
// URI returns the user ID as a MatrixURI struct, which can then be stringified into a matrix: URI or a matrix.to URL. |
| 56 |
// |
| 57 |
// This does not parse or validate the user ID. Use the ParseAndValidate method if you want to ensure the user ID is valid first. |
| 58 |
func (userID UserID) URI() *MatrixURI { |
| 59 |
return &MatrixURI{ |
| 60 |
Sigil1: '@', |
| 61 |
MXID1: string(userID)[1:], |
| 62 |
} |
| 63 |
} |
| 64 |
|
| 65 |
var ValidLocalpartRegex = regexp.MustCompile("^[0-9a-z-.=_/]+$") |
| 66 |
|
| 67 |
// ValidateUserLocalpart validates a Matrix user ID localpart using the grammar |
| 68 |
// in https://matrix.org/docs/spec/appendices#user-identifier |
| 69 |
func ValidateUserLocalpart(localpart string) error { |
| 70 |
if len(localpart) == 0 { |
| 71 |
return ErrEmptyLocalpart |
| 72 |
} else if !ValidLocalpartRegex.MatchString(localpart) { |
| 73 |
return fmt.Errorf("'%s' %w", localpart, ErrNoncompliantLocalpart) |
| 74 |
} |
| 75 |
return nil |
| 76 |
} |
| 77 |
|
| 78 |
// ParseAndValidate parses the user ID into the localpart and server name like Parse, |
| 79 |
// and also validates that the localpart is allowed according to the user identifiers spec. |
| 80 |
func (userID UserID) ParseAndValidate() (localpart, homeserver string, err error) { |
| 81 |
localpart, homeserver, err = userID.Parse() |
| 82 |
if err == nil { |
| 83 |
err = ValidateUserLocalpart(localpart) |
| 84 |
} |
| 85 |
if err == nil && len(userID) > UserIDMaxLength { |
| 86 |
err = ErrUserIDTooLong |
| 87 |
} |
| 88 |
return |
| 89 |
} |
| 90 |
|
| 91 |
func (userID UserID) ParseAndDecode() (localpart, homeserver string, err error) { |
| 92 |
localpart, homeserver, err = userID.ParseAndValidate() |
| 93 |
if err == nil { |
| 94 |
localpart, err = DecodeUserLocalpart(localpart) |
| 95 |
} |
| 96 |
return |
| 97 |
} |
| 98 |
|
| 99 |
func (userID UserID) String() string { |
| 100 |
return string(userID) |
| 101 |
} |
| 102 |
|
| 103 |
const lowerhex = "0123456789abcdef" |
| 104 |
|
| 105 |
// encode the given byte using quoted-printable encoding (e.g "=2f") |
| 106 |
// and writes it to the buffer |
| 107 |
// See https://golang.org/src/mime/quotedprintable/writer.go |
| 108 |
func encode(buf *bytes.Buffer, b byte) { |
| 109 |
buf.WriteByte('=') |
| 110 |
buf.WriteByte(lowerhex[b>>4]) |
| 111 |
buf.WriteByte(lowerhex[b&0x0f]) |
| 112 |
} |
| 113 |
|
| 114 |
// escape the given alpha character and writes it to the buffer |
| 115 |
func escape(buf *bytes.Buffer, b byte) { |
| 116 |
buf.WriteByte('_') |
| 117 |
if b == '_' { |
| 118 |
buf.WriteByte('_') // another _ |
| 119 |
} else { |
| 120 |
buf.WriteByte(b + 0x20) // ASCII shift A-Z to a-z |
| 121 |
} |
| 122 |
} |
| 123 |
|
| 124 |
func shouldEncode(b byte) bool { |
| 125 |
return b != '-' && b != '.' && b != '_' && !(b >= '0' && b <= '9') && !(b >= 'a' && b <= 'z') && !(b >= 'A' && b <= 'Z') |
| 126 |
} |
| 127 |
|
| 128 |
func shouldEscape(b byte) bool { |
| 129 |
return (b >= 'A' && b <= 'Z') || b == '_' |
| 130 |
} |
| 131 |
|
| 132 |
func isValidByte(b byte) bool { |
| 133 |
return isValidEscapedChar(b) || (b >= '0' && b <= '9') || b == '.' || b == '=' || b == '-' |
| 134 |
} |
| 135 |
|
| 136 |
func isValidEscapedChar(b byte) bool { |
| 137 |
return b == '_' || (b >= 'a' && b <= 'z') |
| 138 |
} |
| 139 |
|
| 140 |
// EncodeUserLocalpart encodes the given string into Matrix-compliant user ID localpart form. |
| 141 |
// See https://spec.matrix.org/v1.2/appendices/#mapping-from-other-character-sets |
| 142 |
// |
| 143 |
// This returns a string with only the characters "a-z0-9._=-". The uppercase range A-Z |
| 144 |
// are encoded using leading underscores ("_"). Characters outside the aforementioned ranges |
| 145 |
// (including literal underscores ("_") and equals ("=")) are encoded as UTF8 code points (NOT NCRs) |
| 146 |
// and converted to lower-case hex with a leading "=". For example: |
| 147 |
// Alph@Bet_50up => _alph=40_bet=5f50up |
| 148 |
func EncodeUserLocalpart(str string) string { |
| 149 |
strBytes := []byte(str) |
| 150 |
var outputBuffer bytes.Buffer |
| 151 |
for _, b := range strBytes { |
| 152 |
if shouldEncode(b) { |
| 153 |
encode(&outputBuffer, b) |
| 154 |
} else if shouldEscape(b) { |
| 155 |
escape(&outputBuffer, b) |
| 156 |
} else { |
| 157 |
outputBuffer.WriteByte(b) |
| 158 |
} |
| 159 |
} |
| 160 |
return outputBuffer.String() |
| 161 |
} |
| 162 |
|
| 163 |
// DecodeUserLocalpart decodes the given string back into the original input string. |
| 164 |
// Returns an error if the given string is not a valid user ID localpart encoding. |
| 165 |
// See https://spec.matrix.org/v1.2/appendices/#mapping-from-other-character-sets |
| 166 |
// |
| 167 |
// This decodes quoted-printable bytes back into UTF8, and unescapes casing. For |
| 168 |
// example: |
| 169 |
// _alph=40_bet=5f50up => Alph@Bet_50up |
| 170 |
// Returns an error if the input string contains characters outside the |
| 171 |
// range "a-z0-9._=-", has an invalid quote-printable byte (e.g. not hex), or has |
| 172 |
// an invalid _ escaped byte (e.g. "_5"). |
| 173 |
func DecodeUserLocalpart(str string) (string, error) { |
| 174 |
strBytes := []byte(str) |
| 175 |
var outputBuffer bytes.Buffer |
| 176 |
for i := 0; i < len(strBytes); i++ { |
| 177 |
b := strBytes[i] |
| 178 |
if !isValidByte(b) { |
| 179 |
return "", fmt.Errorf("Byte pos %d: Invalid byte", i) |
| 180 |
} |
| 181 |
|
| 182 |
if b == '_' { // next byte is a-z and should be upper-case or is another _ and should be a literal _ |
| 183 |
if i+1 >= len(strBytes) { |
| 184 |
return "", fmt.Errorf("Byte pos %d: expected _[a-z_] encoding but ran out of string", i) |
| 185 |
} |
| 186 |
if !isValidEscapedChar(strBytes[i+1]) { // invalid escaping |
| 187 |
return "", fmt.Errorf("Byte pos %d: expected _[a-z_] encoding", i) |
| 188 |
} |
| 189 |
if strBytes[i+1] == '_' { |
| 190 |
outputBuffer.WriteByte('_') |
| 191 |
} else { |
| 192 |
outputBuffer.WriteByte(strBytes[i+1] - 0x20) // ASCII shift a-z to A-Z |
| 193 |
} |
| 194 |
i++ // skip next byte since we just handled it |
| 195 |
} else if b == '=' { // next 2 bytes are hex and should be buffered ready to be read as utf8 |
| 196 |
if i+2 >= len(strBytes) { |
| 197 |
return "", fmt.Errorf("Byte pos: %d: expected quote-printable encoding but ran out of string", i) |
| 198 |
} |
| 199 |
dst := make([]byte, 1) |
| 200 |
_, err := hex.Decode(dst, strBytes[i+1:i+3]) |
| 201 |
if err != nil { |
| 202 |
return "", err |
| 203 |
} |
| 204 |
outputBuffer.WriteByte(dst[0]) |
| 205 |
i += 2 // skip next 2 bytes since we just handled it |
| 206 |
} else { // pass through |
| 207 |
outputBuffer.WriteByte(b) |
| 208 |
} |
| 209 |
} |
| 210 |
return outputBuffer.String(), nil |
| 211 |
} |