gomatrixserverlib

package module
v0.0.0-...-768a876 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 24, 2017 License: Apache-2.0 Imports: 22 Imported by: 0

README

gomatrixserverlib

GoDoc

Go library for common functions needed by matrix servers.

Documentation

Index

Examples

Constants

View Source
const (

	// MRoomCreate https://matrix.org/docs/spec/client_server/r0.2.0.html#m-room-create
	MRoomCreate = "m.room.create"
	// MRoomJoinRules https://matrix.org/docs/spec/client_server/r0.2.0.html#m-room-join-rules
	MRoomJoinRules = "m.room.join_rules"
	// MRoomPowerLevels https://matrix.org/docs/spec/client_server/r0.2.0.html#m-room-power-levels
	MRoomPowerLevels = "m.room.power_levels"
	// MRoomMember https://matrix.org/docs/spec/client_server/r0.2.0.html#m-room-member
	MRoomMember = "m.room.member"
	// MRoomThirdPartyInvite https://matrix.org/docs/spec/client_server/r0.2.0.html#m-room-third-party-invite
	MRoomThirdPartyInvite = "m.room.third_party_invite"
	// MRoomAliases https://matrix.org/docs/spec/client_server/r0.2.0.html#m-room-aliases
	MRoomAliases = "m.room.aliases"
	// MRoomHistoryVisibility https://matrix.org/docs/spec/client_server/r0.2.0.html#m-room-history-visibility
	MRoomHistoryVisibility = "m.room.history_visibility"
	// MRoomRedaction https://matrix.org/docs/spec/client_server/r0.2.0.html#id21
	MRoomRedaction = "m.room.redaction"
)

Variables

This section is empty.

Functions

func Allowed

func Allowed(event Event, authEvents AuthEventProvider) error

Allowed checks whether an event is allowed by the auth events. It returns a NotAllowed error if the event is not allowed. If there was an error loading the auth events then it returns that error.

func CanonicalJSON

func CanonicalJSON(input []byte) ([]byte, error)

CanonicalJSON re-encodes the JSON in a canonical encoding. The encoding is the shortest possible encoding using integer values with sorted object keys. https://matrix.org/docs/spec/server_server/unstable.html#canonical-json

func CheckKeys

func CheckKeys(serverName ServerName, now time.Time, keys ServerKeys, connState *tls.ConnectionState) (
	checks KeyChecks, ed25519Keys map[KeyID]Base64String, sha256Fingerprints []Base64String,
)

CheckKeys checks the keys returned from a server to make sure they are valid. If the checks pass then also return a map of key_id to Ed25519 public key and a list of SHA256 TLS fingerprints.

func CompactJSON

func CompactJSON(input, output []byte) []byte

CompactJSON makes the encoded JSON as small as possible by removing whitespace and unneeded unicode escapes

func SignJSON

func SignJSON(signingName string, keyID KeyID, privateKey ed25519.PrivateKey, message []byte) ([]byte, error)

SignJSON signs a JSON object returning a copy signed with the given key. https://matrix.org/docs/spec/server_server/unstable.html#signing-json

func SortJSON

func SortJSON(input, output []byte) ([]byte, error)

SortJSON reencodes the JSON with the object keys sorted by lexicographically by codepoint. The input must be valid JSON.

func VerifyEventSignatures

func VerifyEventSignatures(events []Event, keyRing KeyRing) error

VerifyEventSignatures checks that each event in a list of events has valid signatures from the server that sent it.

func VerifyJSON

func VerifyJSON(signingName string, keyID KeyID, publicKey ed25519.PublicKey, message []byte) error

VerifyJSON checks that the entity has signed the message using a particular key.

Types

type AuthEventProvider

type AuthEventProvider interface {
	// Create returns the m.room.create event for the room or nil if there isn't a m.room.create event.
	Create() (*Event, error)
	// JoinRules returns the m.room.join_rules event for the room or nil if there isn't a m.room.join_rules event.
	JoinRules() (*Event, error)
	// PowerLevels returns the m.room.power_levels event for the room or nil if there isn't a m.room.power_levels event.
	PowerLevels() (*Event, error)
	// Member returns the m.room.member event for the given user_id state_key or nil if there isn't a m.room.member event.
	Member(stateKey string) (*Event, error)
	// ThirdPartyInvite returns the m.room.third_party_invite event for the
	// given state_key or nil if there isn't a m.room.third_party_invite event
	ThirdPartyInvite(stateKey string) (*Event, error)
}

AuthEventProvider provides auth_events for the authentication checks.

type AuthEvents

type AuthEvents struct {
	// contains filtered or unexported fields
}

AuthEvents is an implementation of AuthEventProvider backed by a map.

func NewAuthEvents

func NewAuthEvents(events []*Event) AuthEvents

NewAuthEvents returns an AuthEventProvider backed by the given events. New events can be added by calling AddEvent().

func (*AuthEvents) AddEvent

func (a *AuthEvents) AddEvent(event *Event) error

AddEvent adds an event to the provider. If an event already existed for the (type, state_key) then the event is replaced with the new event. Only returns an error if the event is not a state event.

func (*AuthEvents) Create

func (a *AuthEvents) Create() (*Event, error)

Create implements AuthEventProvider

func (*AuthEvents) JoinRules

func (a *AuthEvents) JoinRules() (*Event, error)

JoinRules implements AuthEventProvider

func (*AuthEvents) Member

func (a *AuthEvents) Member(stateKey string) (*Event, error)

Member implements AuthEventProvider

func (*AuthEvents) PowerLevels

func (a *AuthEvents) PowerLevels() (*Event, error)

PowerLevels implements AuthEventProvider

func (*AuthEvents) ThirdPartyInvite

func (a *AuthEvents) ThirdPartyInvite(stateKey string) (*Event, error)

ThirdPartyInvite implements AuthEventProvider

type Base64String

type Base64String []byte

A Base64String is a string of bytes that are base64 encoded when used in JSON. The bytes encoded using base64 when marshalled as JSON. When the bytes are unmarshalled from JSON they are decoded from base64.

func (Base64String) MarshalJSON

func (b64 Base64String) MarshalJSON() ([]byte, error)

MarshalJSON encodes the bytes as base64 and then encodes the base64 as a JSON string. This takes a value receiver so that maps and slices of Base64String encode correctly.

func (*Base64String) UnmarshalJSON

func (b64 *Base64String) UnmarshalJSON(raw []byte) (err error)

UnmarshalJSON decodes a JSON string and then decodes the resulting base64. This takes a pointer receiver because it needs to write the result of decoding.

type Client

type Client struct {
	// contains filtered or unexported fields
}

A Client makes request to the federation listeners of matrix homeservers

func NewClient

func NewClient() *Client

NewClient makes a new Client

func (*Client) CreateMediaDownloadRequest

func (fc *Client) CreateMediaDownloadRequest(matrixServer ServerName, mediaID string) (*http.Response, error)

CreateMediaDownloadRequest creates a request for media on a homeserver and returns the http.Response or an error

func (*Client) LookupServerKeys

func (fc *Client) LookupServerKeys(
	matrixServer ServerName, keyRequests map[PublicKeyRequest]Timestamp,
) (map[PublicKeyRequest]ServerKeys, error)

LookupServerKeys lookups up the keys for a matrix server from a matrix server. The first argument is the name of the matrix server to download the keys from. The second argument is a map from (server name, key ID) pairs to timestamps. The (server name, key ID) pair identifies the key to download. The timestamps tell the server when the keys need to be valid until. Perspective servers can use that timestamp to determine whether they can return a cached copy of the keys or whether they will need to retrieve a fresh copy of the keys. Returns the keys or an error if there was a problem talking to the server.

func (*Client) LookupUserInfo

func (fc *Client) LookupUserInfo(matrixServer ServerName, token string) (u UserInfo, err error)

LookupUserInfo gets information about a user from a given matrix homeserver using a bearer access token.

type ClientEvent

type ClientEvent struct {
	Content        rawJSON   `json:"content"`
	EventID        string    `json:"event_id"`
	OriginServerTS Timestamp `json:"origin_server_ts"`
	// RoomID is omitted on /sync responses
	RoomID   string  `json:"room_id,omitempty"`
	Sender   string  `json:"sender"`
	StateKey *string `json:"state_key,omitempty"`
	Type     string  `json:"type"`
	Unsigned rawJSON `json:"unsigned,omitempty"`
}

ClientEvent is an event which is fit for consumption by clients, in accordance with the specification.

func ToClientEvent

func ToClientEvent(se Event, format EventFormat) ClientEvent

ToClientEvent converts a single server event to a client event.

func ToClientEvents

func ToClientEvents(serverEvs []Event, format EventFormat) []ClientEvent

ToClientEvents converts server events to client events.

type DNSResult

type DNSResult struct {
	SRVCName   string                // The canonical name for the SRV record in DNS
	SRVRecords []*net.SRV            // List of SRV record for the matrix server.
	SRVError   error                 // If there was an error getting the SRV records.
	Hosts      map[string]HostResult // The results of looking up the SRV record targets.
	Addrs      []string              // List of "<ip>:<port>" strings that the server is listening on. These strings can be passed to `net.Dial()`.
}

A DNSResult is the result of looking up a matrix server in DNS.

func LookupServer

func LookupServer(serverName ServerName) (*DNSResult, error)

LookupServer looks up a matrix server in DNS.

type DirectKeyFetcher

type DirectKeyFetcher struct {
	// The federation client to use to fetch keys with.
	Client Client
}

A DirectKeyFetcher fetches keys directly from a server. This may be suitable for local deployments that are firewalled from the public internet where DNS can be trusted.

func (*DirectKeyFetcher) FetchKeys

func (d *DirectKeyFetcher) FetchKeys(requests map[PublicKeyRequest]Timestamp) (map[PublicKeyRequest]ServerKeys, error)

FetchKeys implements KeyFetcher

type Ed25519Checks

type Ed25519Checks struct {
	ValidEd25519      bool // The verify key is valid Ed25519 keys.
	MatchingSignature bool // The verify key has a valid signature.
}

Ed25519Checks are the checks that are applied to Ed25519 keys in ServerKey responses.

type Event

type Event struct {
	// contains filtered or unexported fields
}

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.

func NewEventFromTrustedJSON

func NewEventFromTrustedJSON(eventJSON []byte, redacted bool) (result Event, err error)

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 NewEventFromUntrustedJSON

func NewEventFromUntrustedJSON(eventJSON []byte) (result Event, err error)

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 ResolveStateConflicts

func ResolveStateConflicts(conflicted []Event, authEvents []Event) []Event

ResolveStateConflicts takes a list of state events with conflicting state keys and works out which event should be used for each state event.

func (Event) AuthEventIDs

func (e Event) AuthEventIDs() []string

AuthEventIDs returns the event IDs of the events needed to auth the event.

func (Event) AuthEvents

func (e Event) AuthEvents() []EventReference

AuthEvents returns references to the events needed to auth the event.

func (Event) CheckFields

func (e Event) CheckFields() error

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 (Event) Content

func (e Event) Content() []byte

Content returns the content JSON of the event.

func (Event) Depth

func (e Event) Depth() int64

Depth returns the depth of the event.

func (Event) EventID

func (e Event) EventID() string

EventID returns the event ID of the event.

func (Event) EventReference

func (e Event) EventReference() EventReference

EventReference returns an EventReference for the event. The reference can be used to refer to this event from other events.

func (Event) JSON

func (e Event) JSON() []byte

JSON returns the JSON bytes for the event.

func (Event) KeyIDs

func (e Event) KeyIDs(signingName string) []KeyID

KeyIDs returns a list of key IDs that the named entity has signed the event with.

func (Event) MarshalJSON

func (e Event) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaller

func (Event) Membership

func (e Event) Membership() (string, error)

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 (Event) Origin

func (e Event) Origin() ServerName

Origin returns the name of the server that sent the event

func (Event) OriginServerTS

func (e Event) OriginServerTS() Timestamp

OriginServerTS returns the unix timestamp when this event was created on the origin server, with millisecond resolution.

func (Event) PrevEventIDs

func (e Event) PrevEventIDs() []string

PrevEventIDs returns the event IDs of the direct ancestors of the event.

func (Event) PrevEvents

func (e Event) PrevEvents() []EventReference

PrevEvents returns references to the direct ancestors of the event.

func (Event) Redact

func (e Event) Redact() Event

Redact returns a redacted copy of the event.

func (Event) Redacted

func (e Event) Redacted() bool

Redacted returns whether the event is redacted.

func (Event) Redacts

func (e Event) Redacts() string

Redacts returns the event ID of the event this event redacts.

func (Event) RoomID

func (e Event) RoomID() string

RoomID returns the room ID of the room the event is in.

func (Event) Sender

func (e Event) Sender() string

Sender returns the user ID of the sender of the event.

func (Event) SetUnsigned

func (e Event) SetUnsigned(unsigned interface{}) (Event, error)

SetUnsigned sets the unsigned key of the event. Returns a copy of the event with the "unsigned" key set.

func (Event) Sign

func (e Event) Sign(signingName string, keyID KeyID, privateKey ed25519.PrivateKey) Event

Sign returns a copy of the event with an additional signature.

func (Event) StateKey

func (e Event) StateKey() *string

StateKey returns the "state_key" of the event, or the nil if the event is not a state event.

func (Event) StateKeyEquals

func (e Event) StateKeyEquals(stateKey string) bool

StateKeyEquals returns true if the event is a state event and the "state_key" matches.

func (Event) Type

func (e Event) Type() string

Type returns the type of the event.

func (*Event) UnmarshalJSON

func (e *Event) UnmarshalJSON(data []byte) (err error)

UnmarshalJSON implements json.Unmarshaller assuming the Event is from an untrusted source. This will cause more checks than might be necessary but is probably better to be safe than sorry.

func (Event) Unsigned

func (e Event) Unsigned() []byte

Unsigned returns the object under the 'unsigned' key of the event.

func (Event) Verify

func (e Event) Verify(signingName string, keyID KeyID, publicKey ed25519.PublicKey) error

Verify checks a ed25519 signature

type EventBuilder

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.
	PrevEvents []EventReference `json:"prev_events"`
	// The events needed to authenticate this event.
	AuthEvents []EventReference `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 "content" key of the event.
	Content rawJSON `json:"content"`
	// The JSON object for the "unsigned" key
	Unsigned rawJSON `json:"unsigned,omitempty"`
}

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.

func (*EventBuilder) Build

func (eb *EventBuilder) Build(eventID string, now time.Time, origin ServerName, keyID KeyID, privateKey ed25519.PrivateKey) (result Event, err error)

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 (*EventBuilder) SetContent

func (eb *EventBuilder) SetContent(content interface{}) (err error)

SetContent sets the JSON content key of the event.

func (*EventBuilder) SetUnsigned

func (eb *EventBuilder) SetUnsigned(unsigned interface{}) (err error)

SetUnsigned sets the JSON unsigned key of the event.

type EventFormat

type EventFormat int

EventFormat specifies the format of a client event

const (
	// FormatAll will include all client event keys
	FormatAll EventFormat = iota
	// FormatSync will include only the event keys required by the /sync API. Notably, this
	// means the 'room_id' will be missing from the events.
	FormatSync
)

type EventReference

type EventReference struct {
	// The event ID of the event.
	EventID string
	// The sha256 of the redacted event.
	EventSHA256 Base64String
}

An EventReference is a reference to a matrix event.

func (EventReference) MarshalJSON

func (er EventReference) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaller

func (*EventReference) UnmarshalJSON

func (er *EventReference) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaller

type FederationClient

type FederationClient struct {
	Client
	// contains filtered or unexported fields
}

An FederationClient is a matrix federation client that adds "Authorization: X-Matrix" headers to requests that need ed25519 signatures

func NewFederationClient

func NewFederationClient(
	serverName ServerName, keyID KeyID, privateKey ed25519.PrivateKey,
) *FederationClient

NewFederationClient makes a new FederationClient

func (*FederationClient) LookupRoomAlias

func (ac *FederationClient) LookupRoomAlias(s ServerName, roomAlias string) (res RespDirectory, err error)

LookupRoomAlias looks up a room alias hosted on the remote server. The domain part of the roomAlias must match the name of the server it is being looked up on. If the room alias doesn't exist on the remote server then a 404 gomatrix.HTTPError is returned.

func (*FederationClient) LookupState

func (ac *FederationClient) LookupState(s ServerName, roomID, eventID string) (res RespState, err error)

LookupState retrieves the room state for a room at an event from a remote matrix server as full matrix events.

func (*FederationClient) LookupStateIDs

func (ac *FederationClient) LookupStateIDs(s ServerName, roomID, eventID string) (res RespStateIDs, err error)

LookupStateIDs retrieves the room state for a room at an event from a remote matrix server as lists of matrix event IDs.

func (*FederationClient) MakeJoin

func (ac *FederationClient) MakeJoin(s ServerName, roomID, userID string) (res RespMakeJoin, err error)

MakeJoin makes a join m.room.member event for a room on a remote matrix server. This is used to join a room the local server isn't a member of. We need to query a remote server because if we aren't in the room we don't know what to use for the "prev_events" in the join event. The remote server should return us a m.room.member event for our local user with the "prev_events" filled out. If this successfully returns an acceptable event we will sign it with our server's key and pass it to SendJoin. See https://matrix.org/docs/spec/server_server/unstable.html#joining-rooms

func (*FederationClient) SendJoin

func (ac *FederationClient) SendJoin(s ServerName, event Event) (res RespSendJoin, err error)

SendJoin sends a join m.room.member event obtained using MakeJoin via a remote matrix server. This is used to join a room the local server isn't a member of. See https://matrix.org/docs/spec/server_server/unstable.html#joining-rooms

func (*FederationClient) SendTransaction

func (ac *FederationClient) SendTransaction(t Transaction) (res RespSend, err error)

SendTransaction sends a transaction

type FederationRequest

type FederationRequest struct {
	// contains filtered or unexported fields
}

A FederationRequest is a request to send to a remote server or a request received from a remote server. Federation requests are signed by building a JSON object and signing it

func NewFederationRequest

func NewFederationRequest(method string, destination ServerName, requestURI string) FederationRequest

NewFederationRequest creates a matrix request. Takes an HTTP method, a destination homeserver and a request path which can have a query string. The destination is the name of a matrix homeserver. The request path must begin with a slash. Eg. NewFederationRequest("GET", "matrix.org", "/_matrix/federation/v1/send/123")

func VerifyHTTPRequest

func VerifyHTTPRequest(
	req *http.Request, now time.Time, destination ServerName, keys KeyRing,
) (*FederationRequest, util.JSONResponse)

VerifyHTTPRequest extracts and verifies the contents of a net/http.Request. It consumes the body of the request. The JSON content can be accessed using FederationRequest.Content() Returns an 400 error if there was a problem parsing the request. It authenticates the request using an ed25519 signature using the KeyRing. The origin server can be accessed using FederationRequest.Origin() Returns a 401 error if there was a problem authenticating the request. HTTP handlers using this should be careful that they only use the parts of the request that have been authenticated: the method, the request path, the query parameters, and the JSON content. In particular the version of HTTP and the headers aren't protected by the signature.

func (*FederationRequest) Content

func (r *FederationRequest) Content() []byte

Content returns the JSON content for the request.

func (*FederationRequest) HTTPRequest

func (r *FederationRequest) HTTPRequest() (*http.Request, error)

HTTPRequest constructs an net/http.Request for this matrix request. The request can be passed to net/http.Client.Do().

func (*FederationRequest) Method

func (r *FederationRequest) Method() string

Method returns the JSON method for the request.

func (*FederationRequest) Origin

func (r *FederationRequest) Origin() ServerName

Origin returns the server that the request originated on.

func (*FederationRequest) RequestURI

func (r *FederationRequest) RequestURI() string

RequestURI returns the path and query sections of the HTTP request URL.

func (*FederationRequest) SetContent

func (r *FederationRequest) SetContent(content interface{}) error

SetContent sets the JSON content for the request. Returns an error if there already is JSON content present on the request.

func (*FederationRequest) Sign

func (r *FederationRequest) Sign(serverName ServerName, keyID KeyID, privateKey ed25519.PrivateKey) error

Sign the matrix request with an ed25519 key. Uses the algorithm specified https://matrix.org/docs/spec/server_server/unstable.html#request-authentication Updates the request with the signature in place. Returns an error if there was a problem signing the request.

type HostResult

type HostResult struct {
	CName string   // The canonical name for the host.
	Addrs []string // The IP addresses for the host.
	Error error    // If there was an error getting the IP addresses.
}

A HostResult is the result of looking up the IP addresses for a host.

type KeyChecks

type KeyChecks struct {
	AllChecksOK               bool                    // Did all the checks pass?
	MatchingServerName        bool                    // Does the server name match what was requested.
	FutureValidUntilTS        bool                    // The valid until TS is in the future.
	HasEd25519Key             bool                    // The server has at least one ed25519 key.
	AllEd25519ChecksOK        *bool                   // All the Ed25519 checks are ok. or null if there weren't any to check.
	Ed25519Checks             map[KeyID]Ed25519Checks // Checks for Ed25519 keys.
	HasTLSFingerprint         bool                    // The server has at least one fingerprint.
	AllTLSFingerprintChecksOK *bool                   // All the fingerprint checks are ok.
	TLSFingerprintChecks      []TLSFingerprintChecks  // Checks for TLS fingerprints.
	MatchingTLSFingerprint    *bool                   // The TLS fingerprint for the connection matches one of the listed fingerprints.
}

KeyChecks are the checks that should be applied to ServerKey responses.

type KeyDatabase

type KeyDatabase interface {
	KeyFetcher
	// Add a block of public keys to the database.
	// Returns an error if there was a problem storing the keys.
	// A database is not required to rollback storing the all keys if some of
	// the keys aren't stored, and an in-progess store may be partially visible
	// to a concurrent FetchKeys(). This is acceptable since the database is
	// only used as a cache for the keys, so if a FetchKeys() races with a
	// StoreKeys() and some of the keys are missing they will be just be refetched.
	StoreKeys(map[PublicKeyRequest]ServerKeys) error
}

A KeyDatabase is a store for caching public keys.

type KeyFetcher

type KeyFetcher interface {
	// Lookup a batch of public keys.
	// Takes a map from (server name, key ID) pairs to timestamp.
	// The timestamp is when the keys need to be vaild up to.
	// Returns a map from (server name, key ID) pairs to server key objects for
	// that server name containing that key ID
	// The result may have fewer (server name, key ID) pairs than were in the request.
	// The result may have more (server name, key ID) pairs than were in the request.
	// Returns an error if there was a problem fetching the keys.
	FetchKeys(requests map[PublicKeyRequest]Timestamp) (map[PublicKeyRequest]ServerKeys, error)
}

A KeyFetcher is a way of fetching public keys in bulk.

type KeyID

type KeyID string

A KeyID is the ID of a ed25519 key used to sign JSON. The key IDs have a format of "ed25519:[0-9A-Za-z]+" If we switch to using a different signing algorithm then we will change the prefix used.

func ListKeyIDs

func ListKeyIDs(signingName string, message []byte) ([]KeyID, error)

ListKeyIDs lists the key IDs a given entity has signed a message with.

type KeyRing

type KeyRing struct {
	KeyFetchers []KeyFetcher
	KeyDatabase KeyDatabase
}

A KeyRing stores keys for matrix servers and provides methods for verifying JSON messages.

func (*KeyRing) VerifyJSONs

func (k *KeyRing) VerifyJSONs(requests []VerifyJSONRequest) ([]VerifyJSONResult, error)

VerifyJSONs performs bulk JSON signature verification for a list of VerifyJSONRequests. Returns a list of VerifyJSONResults with the same length and order as the request list. The caller should check the Result field for each entry to see if it was valid. Returns an error if there was a problem talking to the database or one of the other methods of fetching the public keys.

type NotAllowed

type NotAllowed struct {
	Message string
}

A NotAllowed error is returned if an event does not pass the auth checks.

func (*NotAllowed) Error

func (a *NotAllowed) Error() string

type OldVerifyKey

type OldVerifyKey struct {
	VerifyKey
	// When this key stopped being valid for event signing in milliseconds.
	ExpiredTS Timestamp `json:"expired_ts"`
}

An OldVerifyKey is an old ed25519 public key that is no longer valid.

type PDUResult

type PDUResult struct {
	// If not empty then this is a human readable description of a problem
	// encountered processing an event.
	Error string `json:"error,omitempty"`
}

A PDUResult is the result of processing a matrix room event.

type PerspectiveKeyFetcher

type PerspectiveKeyFetcher struct {
	// The name of the perspective server to fetch keys from.
	PerspectiveServerName ServerName
	// The ed25519 public keys the perspective server must sign responses with.
	PerspectiveServerKeys map[KeyID]ed25519.PublicKey
	// The federation client to use to fetch keys with.
	Client Client
}

A PerspectiveKeyFetcher fetches server keys from a single perspective server.

func (*PerspectiveKeyFetcher) FetchKeys

FetchKeys implements KeyFetcher

type PublicKeyRequest

type PublicKeyRequest struct {
	// The server to fetch a key for.
	ServerName ServerName
	// The ID of the key to fetch.
	KeyID KeyID
}

A PublicKeyRequest is a request for a public key with a particular key ID.

type RespDirectory

type RespDirectory struct {
	// The matrix room ID the room alias corresponds to.
	RoomID string `json:"room_id"`
	// A list of matrix servers that the directory server thinks could be used
	// to join the room. The joining server may need to try multiple servers
	// before it finds one that it can use to join the room.
	Servers []ServerName `json:"servers"`
}

A RespDirectory is the content of a response to GET /_matrix/federation/v1/query/directory This is returned when looking up a room alias from a remote server. See https://matrix.org/docs/spec/server_server/unstable.html#directory

type RespMakeJoin

type RespMakeJoin struct {
	// An incomplete m.room.member event for a user on the requesting server
	// generated by the responding server.
	// See https://matrix.org/docs/spec/server_server/unstable.html#joining-rooms
	JoinEvent EventBuilder `json:"event"`
}

A RespMakeJoin is the content of a response to GET /_matrix/federation/v1/make_join/{roomID}/{userID}

type RespSend

type RespSend struct {
	// Map of event ID to the result of processing that event.
	PDUs map[string]PDUResult `json:"pdus"`
}

A RespSend is the content of a response to PUT /_matrix/federation/v1/send/{txnID}/

type RespSendJoin

type RespSendJoin RespState

A RespSendJoin is the content of a response to PUT /_matrix/federation/v1/send_join/{roomID}/{eventID} It has the same data as a response to /state, but in a slightly different wire format.

func (RespSendJoin) Check

func (r RespSendJoin) Check(keyRing KeyRing, joinEvent Event) error

Check that a response to /send_join is valid. This checks that it would be valid as a response to /state This also checks that the join event is allowed by the state.

func (RespSendJoin) MarshalJSON

func (r RespSendJoin) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaller

func (*RespSendJoin) UnmarshalJSON

func (r *RespSendJoin) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaller

type RespState

type RespState struct {
	// A list of events giving the state of the room before the request event.
	StateEvents []Event `json:"pdus"`
	// A list of events needed to authenticate the state events.
	AuthEvents []Event `json:"auth_chain"`
}

A RespState is the content of a response to GET /_matrix/federation/v1/state/{roomID}/{eventID}

func (RespState) Check

func (r RespState) Check(keyRing KeyRing) error

Check that a response to /state is valid.

func (RespState) Events

func (r RespState) Events() ([]Event, error)

Events combines the auth events and the state events and returns them in an order where every event comes after its auth events. Each event will only appear once in the output list. Returns an error if there are missing auth events or if there is a cycle in the auth events.

type RespStateIDs

type RespStateIDs struct {
	// A list of state event IDs for the state of the room before the requested event.
	StateEventIDs []string `json:"pdu_ids"`
	// A list of event IDs needed to authenticate the state events.
	AuthEventIDs []string `json:"auth_chain_ids"`
}

A RespStateIDs is the content of a response to GET /_matrix/federation/v1/state_ids/{roomID}/{eventID}

type ServerKeyFields

type ServerKeyFields struct {
	// The name of the server
	ServerName ServerName `json:"server_name"`
	// List of SHA256 fingerprints of X509 certificates used by this server.
	TLSFingerprints []TLSFingerprint `json:"tls_fingerprints"`
	// The current signing keys in use on this server.
	// The keys of the map are the IDs of the keys.
	// These are valid while this response is valid.
	VerifyKeys map[KeyID]VerifyKey `json:"verify_keys"`
	// When this result is valid until in milliseconds.
	ValidUntilTS Timestamp `json:"valid_until_ts"`
	// Old keys that are now only valid for checking historic events.
	// The keys of the map are the IDs of the keys.
	OldVerifyKeys map[KeyID]OldVerifyKey `json:"old_verify_keys"`
}

ServerKeyFields are the parsed JSON contents of the ed25519 signing keys published by a matrix server.

type ServerKeys

type ServerKeys struct {
	// Copy of the raw JSON for signature checking.
	Raw []byte
	// The server the raw JSON was downloaded from.
	FromServer ServerName
	// The decoded JSON fields.
	ServerKeyFields
}

ServerKeys are the ed25519 signing keys published by a matrix server. Contains SHA256 fingerprints of the TLS X509 certificates used by the server.

func FetchKeysDirect

func FetchKeysDirect(serverName ServerName, addr, sni string) (*ServerKeys, *tls.ConnectionState, error)

FetchKeysDirect fetches the matrix keys directly from the given address. Optionally sets a SNI header if “sni“ is not empty. Returns the server keys and the state of the TLS connection used to retrieve them.

func (ServerKeys) MarshalJSON

func (keys ServerKeys) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler

func (ServerKeys) PublicKey

func (keys ServerKeys) PublicKey(keyID KeyID, atTS Timestamp) []byte

PublicKey returns a public key with the given ID valid at the given TS or nil if no such key exists.

func (*ServerKeys) UnmarshalJSON

func (keys *ServerKeys) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler

type ServerName

type ServerName string

A ServerName is the name a matrix homeserver is identified by. It is a DNS name without a trailing dot optionally followed by a port. So it has the format: "[0-9A-Za-z\-]+(\.[0-9A-Za-z\-]+)*(:[0-9]+)?"

func SplitID

func SplitID(sigil byte, id string) (local string, domain ServerName, err error)

SplitID splits a matrix ID into a local part and a server name.

Example
localpart, domain, err := SplitID('@', "@alice:localhost:8080")
if err != nil {
	panic(err)
}
fmt.Println(localpart, domain)
Output:

alice localhost:8080

type StateKeyTuple

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
}

A StateKeyTuple is the combination of an event type and an event state key. It is often used as a key in maps.

type StateNeeded

type StateNeeded struct {
	// Is the m.room.create event needed to auth the event.
	Create bool
	// Is the m.room.join_rules event needed to auth the event.
	JoinRules bool
	// Is the m.room.power_levels event needed to auth the event.
	PowerLevels bool
	// List of m.room.member state_keys needed to auth the event
	Member []string
	// List of m.room.third_party_invite state_keys
	ThirdPartyInvite []string
}

StateNeeded lists the event types and state_keys needed to authenticate an event.

func StateNeededForAuth

func StateNeededForAuth(events []Event) (result StateNeeded)

StateNeededForAuth returns the event types and state_keys needed to authenticate an event. This takes a list of events to facilitate bulk processing when doing auth checks as part of state conflict resolution.

func StateNeededForEventBuilder

func StateNeededForEventBuilder(builder *EventBuilder) (result StateNeeded, err error)

StateNeededForEventBuilder returns the event types and state_keys needed to authenticate the event being built. These events should be put under 'auth_events' for the event being built. Returns an error if the state needed could not be calculated with the given builder, e.g if there is a m.room.member without a membership key.

func (StateNeeded) AuthEventReferences

func (s StateNeeded) AuthEventReferences(provider AuthEventProvider) (refs []EventReference, err error)

AuthEventReferences returns the auth_events references for the StateNeeded. Returns an error if the provider returns an error. If an event is missing from the provider but is required in StateNeeded, it is skipped over: no error is returned.

func (StateNeeded) Tuples

func (s StateNeeded) Tuples() (res []StateKeyTuple)

Tuples returns the needed state key tuples for performing auth on an event.

type TLSFingerprint

type TLSFingerprint struct {
	SHA256 Base64String `json:"sha256"`
}

A TLSFingerprint is a SHA256 hash of an X509 certificate.

type TLSFingerprintChecks

type TLSFingerprintChecks struct {
	ValidSHA256 bool // The TLS fingerprint includes a valid SHA-256 hash.
}

TLSFingerprintChecks are the checks that are applied to TLS fingerprints in ServerKey responses.

type Timestamp

type Timestamp uint64

A Timestamp is a millisecond posix timestamp.

func AsTimestamp

func AsTimestamp(t time.Time) Timestamp

AsTimestamp turns a time.Time into a millisecond posix timestamp.

func (Timestamp) Time

func (t Timestamp) Time() time.Time

Time turns a millisecond posix timestamp into a UTC time.Time

type Transaction

type Transaction struct {
	// The ID of the transaction.
	TransactionID TransactionID `json:"transaction_id"`
	// The server that sent the transaction.
	Origin ServerName `json:"origin"`
	// The server that should receive the transaction.
	Destination ServerName `json:"destination"`
	// The millisecond posix timestamp on the origin server when the
	// transaction was created.
	OriginServerTS Timestamp `json:"origin_server_ts"`
	// The IDs of the most recent transactions sent by the origin server to
	// the destination server. Multiple transactions can be sent by the origin
	// server to the destination server in parallel so there may be more than
	// one previous transaction.
	PreviousIDs []TransactionID `json:"previous_ids"`
	// The room events pushed from the origin server to the destination server
	// by this transaction. The events should either be events that originate
	// on the origin server or be join m.room.member events.
	PDUs []Event `json:"pdus"`
}

A Transaction is used to push data from one matrix server to another matrix server.

type TransactionID

type TransactionID string

A TransactionID identifies a transaction sent by a matrix server to another matrix server. The ID must be unique amongst the transactions sent from the origin server to the destination, but doesn't have to be globally unique. The ID must be safe to insert into a URL path segment. The ID should have a format matching '^[0-9A-Za-z\-_]*$'

type UserInfo

type UserInfo struct {
	Sub string `json:"sub"`
}

UserInfo represents information about a user.

type VerifyJSONRequest

type VerifyJSONRequest struct {
	// The name of the matrix server to check for a signature for.
	ServerName ServerName
	// The millisecond posix timestamp the message needs to be valid at.
	AtTS Timestamp
	// The JSON bytes.
	Message []byte
}

A VerifyJSONRequest is a request to check for a signature on a JSON message. A JSON message is valid for a server if the message has at least one valid signature from that server.

type VerifyJSONResult

type VerifyJSONResult struct {
	// Whether the message passed the signature checks.
	// This will be nil if the message passed the checks.
	// This will have an error if the message did not pass the checks.
	Error error
}

A VerifyJSONResult is the result of checking the signature of a JSON message.

type VerifyKey

type VerifyKey struct {
	// The public key.
	Key Base64String `json:"key"`
}

A VerifyKey is a ed25519 public key for a server.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL