crypto

package
v0.18.1-mod-1 Latest Latest
Warning

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

Go to latest
Published: Apr 29, 2024 License: MPL-2.0 Imports: 34 Imported by: 0

Documentation

Index

Constants

View Source
const MinUnwedgeInterval = 1 * time.Hour

Variables

View Source
var (
	ErrCrossSigningKeysNotCached = errors.New("cross-signing private keys not in cache")
	ErrUserSigningKeyNotCached   = errors.New("user-signing private key not in cache")
	ErrSelfSigningKeyNotCached   = errors.New("self-signing private key not in cache")
	ErrSignatureUploadFail       = errors.New("server-side failure uploading signatures")
	ErrCantSignOwnMasterKey      = errors.New("signing your own master key is not allowed")
	ErrCantSignOtherDevice       = errors.New("signing other users' devices is not allowed")
	ErrUserNotInQueryResponse    = errors.New("could not find user in query keys response")
	ErrDeviceNotInQueryResponse  = errors.New("could not find device in query keys response")
	ErrOlmAccountNotLoaded       = errors.New("olm account has not been loaded")

	ErrCrossSigningMasterKeyNotFound = errors.New("cross-signing master key not found")
	ErrMasterKeyMACNotFound          = errors.New("found cross-signing master key, but didn't find corresponding MAC in verification request")
	ErrMismatchingMasterKeyMAC       = errors.New("mismatching cross-signing master key MAC")
)
View Source
var (
	IncorrectEncryptedContentType = errors.New("event content is not instance of *event.EncryptedEventContent")
	NoSessionFound                = errors.New("failed to decrypt megolm event: no session with given ID found")
	DuplicateMessageIndex         = errors.New("duplicate megolm message index")
	WrongRoom                     = errors.New("encrypted megolm event is not intended for this room")
	DeviceKeyMismatch             = errors.New("device keys in event and verified device info do not match")
	SenderKeyMismatch             = errors.New("sender keys in content and megolm session do not match")
	RatchetError                  = errors.New("failed to ratchet session after use")
)
View Source
var (
	UnsupportedAlgorithm                = errors.New("unsupported event encryption algorithm")
	NotEncryptedForMe                   = errors.New("olm event doesn't contain ciphertext for this device")
	UnsupportedOlmMessageType           = errors.New("unsupported olm message type")
	DecryptionFailedWithMatchingSession = errors.New("decryption failed with matching session")
	DecryptionFailedForNormalMessage    = errors.New("decryption failed for normal message")
	SenderMismatch                      = errors.New("mismatched sender in olm payload")
	RecipientMismatch                   = errors.New("mismatched recipient in olm payload")
	RecipientKeyMismatch                = errors.New("mismatched recipient key in olm payload")
)
View Source
var (
	MismatchingDeviceID   = errors.New("mismatching device ID in parameter and keys object")
	MismatchingUserID     = errors.New("mismatching user ID in parameter and keys object")
	MismatchingSigningKey = errors.New("received update for device with different signing key")
	NoSigningKeyFound     = errors.New("didn't find ed25519 signing key")
	NoIdentityKeyFound    = errors.New("didn't find curve25519 identity key")
	InvalidKeySignature   = errors.New("invalid signature on device keys")
)
View Source
var (
	AlreadyShared  = errors.New("group session already shared")
	NoGroupSession = errors.New("no group session created")
)
View Source
var (
	ErrMissingExportPrefix          = errors.New("invalid Matrix key export: missing prefix")
	ErrMissingExportSuffix          = errors.New("invalid Matrix key export: missing suffix")
	ErrUnsupportedExportVersion     = errors.New("unsupported Matrix key export format version")
	ErrMismatchingExportHash        = errors.New("mismatching hash; incorrect passphrase?")
	ErrInvalidExportedAlgorithm     = errors.New("session has unknown algorithm")
	ErrMismatchingExportedSessionID = errors.New("imported session has different ID than expected")
)
View Source
var (
	// Reject a key request without responding
	KeyShareRejectNoResponse = KeyShareRejection{}

	KeyShareRejectBlacklisted   = KeyShareRejection{event.RoomKeyWithheldBlacklisted, "You have been blacklisted by this device"}
	KeyShareRejectUnverified    = KeyShareRejection{event.RoomKeyWithheldUnverified, "This device does not share keys to unverified devices"}
	KeyShareRejectOtherUser     = KeyShareRejection{event.RoomKeyWithheldUnauthorized, "This device does not share keys to other users"}
	KeyShareRejectUnavailable   = KeyShareRejection{event.RoomKeyWithheldUnavailable, "Requested session ID not found on this device"}
	KeyShareRejectInternalError = KeyShareRejection{event.RoomKeyWithheldUnavailable, "An internal error occurred while trying to share the requested session"}
)
View Source
var (
	SessionNotShared = errors.New("session has not been shared")
	SessionExpired   = errors.New("session has expired")
)
View Source
var ErrGroupSessionWithheld error = &event.RoomKeyWithheldEventContent{}
View Source
var PostgresArrayWrapper func(any) interface {
	driver.Valuer
	sql.Scanner
}

Functions

func ExportKeys

func ExportKeys(passphrase string, sessions []*InboundGroupSession) ([]byte, error)

ExportKeys exports the given Megolm sessions with the format specified in the Matrix spec. See https://spec.matrix.org/v1.2/client-server-api/#key-exports

func Fingerprint deprecated

func Fingerprint(key id.SigningKey) string

Deprecated: moved to SigningKey.Fingerprint

func IsShareError

func IsShareError(err error) bool

IsShareError returns true if the error is caused by the lack of an outgoing megolm session and can be solved with OlmMachine.ShareGroupSession

Types

type CrossSigningKeysCache

type CrossSigningKeysCache struct {
	MasterKey      olm.PKSigning
	SelfSigningKey olm.PKSigning
	UserSigningKey olm.PKSigning
}

CrossSigningKeysCache holds the three cross-signing keys for the current user.

func (*CrossSigningKeysCache) PublicKeys

type CrossSigningPublicKeysCache

type CrossSigningPublicKeysCache struct {
	MasterKey      id.Ed25519
	SelfSigningKey id.Ed25519
	UserSigningKey id.Ed25519
}

type CrossSigningSeeds

type CrossSigningSeeds struct {
	MasterKey      []byte
	SelfSigningKey []byte
	UserSigningKey []byte
}

type DecryptedOlmEvent

type DecryptedOlmEvent struct {
	Source *event.Event `json:"-"`

	SenderKey id.SenderKey `json:"-"`

	Sender        id.UserID    `json:"sender"`
	SenderDevice  id.DeviceID  `json:"sender_device"`
	Keys          OlmEventKeys `json:"keys"`
	Recipient     id.UserID    `json:"recipient"`
	RecipientKeys OlmEventKeys `json:"recipient_keys"`

	Type    event.Type    `json:"type"`
	Content event.Content `json:"content"`
}

DecryptedOlmEvent represents an event that was decrypted from an event encrypted with the m.olm.v1.curve25519-aes-sha2 algorithm.

type ExpirationMixin

type ExpirationMixin struct {
	TimeMixin
	MaxAge time.Duration
}

func (*ExpirationMixin) Expired

func (exp *ExpirationMixin) Expired() bool

type ExportedSession

type ExportedSession struct {
	Algorithm         id.Algorithm      `json:"algorithm"`
	ForwardingChains  []string          `json:"forwarding_curve25519_key_chain"`
	RoomID            id.RoomID         `json:"room_id"`
	SenderKey         id.SenderKey      `json:"sender_key"`
	SenderClaimedKeys SenderClaimedKeys `json:"sender_claimed_keys"`
	SessionID         id.SessionID      `json:"session_id"`
	SessionKey        string            `json:"session_key"`
}

type InboundGroupSession

type InboundGroupSession struct {
	Internal olm.InboundGroupSession

	SigningKey id.Ed25519
	SenderKey  id.Curve25519
	RoomID     id.RoomID

	ForwardingChains []string
	RatchetSafety    RatchetSafety

	ReceivedAt       time.Time
	MaxAge           int64
	MaxMessages      int
	IsScheduled      bool
	KeyBackupVersion id.KeyBackupVersion
	// contains filtered or unexported fields
}

func NewInboundGroupSession

func NewInboundGroupSession(senderKey id.SenderKey, signingKey id.Ed25519, roomID id.RoomID, sessionKey string, maxAge time.Duration, maxMessages int, isScheduled bool) (*InboundGroupSession, error)

func (*InboundGroupSession) ID

func (igs *InboundGroupSession) ID() id.SessionID

func (*InboundGroupSession) RatchetTo

func (igs *InboundGroupSession) RatchetTo(index uint32) error

type KeyShareRejection

type KeyShareRejection struct {
	Code   event.RoomKeyWithheldCode
	Reason string
}

type MemoryStore

type MemoryStore struct {
	Account               *OlmAccount
	Sessions              map[id.SenderKey]OlmSessionList
	GroupSessions         map[id.RoomID]map[id.SenderKey]map[id.SessionID]*InboundGroupSession
	WithheldGroupSessions map[id.RoomID]map[id.SenderKey]map[id.SessionID]*event.RoomKeyWithheldEventContent
	OutGroupSessions      map[id.RoomID]*OutboundGroupSession
	SharedGroupSessions   map[id.UserID]map[id.IdentityKey]map[id.SessionID]struct{}
	MessageIndices        map[messageIndexKey]messageIndexValue
	Devices               map[id.UserID]map[id.DeviceID]*id.Device
	CrossSigningKeys      map[id.UserID]map[id.CrossSigningUsage]id.CrossSigningKey
	KeySignatures         map[id.UserID]map[id.Ed25519]map[id.UserID]map[id.Ed25519]string
	OutdatedUsers         map[id.UserID]struct{}
	Secrets               map[id.Secret]string
	// contains filtered or unexported fields
}

MemoryStore is a simple in-memory Store implementation. It can optionally have a callback function for saving data, but the actual storage must be implemented manually.

func NewMemoryStore

func NewMemoryStore(saveCallback func() error) *MemoryStore

func (*MemoryStore) AddOutboundGroupSession

func (gs *MemoryStore) AddOutboundGroupSession(_ context.Context, session *OutboundGroupSession) error

func (*MemoryStore) AddSession

func (gs *MemoryStore) AddSession(_ context.Context, senderKey id.SenderKey, session *OlmSession) error

func (*MemoryStore) DeleteSecret

func (gs *MemoryStore) DeleteSecret(_ context.Context, name id.Secret) error

func (*MemoryStore) DropSignaturesByKey

func (gs *MemoryStore) DropSignaturesByKey(_ context.Context, userID id.UserID, key id.Ed25519) (int64, error)

func (*MemoryStore) FilterTrackedUsers

func (gs *MemoryStore) FilterTrackedUsers(_ context.Context, users []id.UserID) ([]id.UserID, error)

func (*MemoryStore) FindDeviceByKey

func (gs *MemoryStore) FindDeviceByKey(_ context.Context, userID id.UserID, identityKey id.IdentityKey) (*id.Device, error)

func (*MemoryStore) Flush

func (gs *MemoryStore) Flush(_ context.Context) error

func (*MemoryStore) GetAccount

func (gs *MemoryStore) GetAccount(_ context.Context) (*OlmAccount, error)

func (*MemoryStore) GetAllGroupSessions

func (gs *MemoryStore) GetAllGroupSessions(_ context.Context) dbutil.RowIter[*InboundGroupSession]

func (*MemoryStore) GetCrossSigningKeys

func (gs *MemoryStore) GetCrossSigningKeys(_ context.Context, userID id.UserID) (map[id.CrossSigningUsage]id.CrossSigningKey, error)

func (*MemoryStore) GetDevice

func (gs *MemoryStore) GetDevice(_ context.Context, userID id.UserID, deviceID id.DeviceID) (*id.Device, error)

func (*MemoryStore) GetDevices

func (gs *MemoryStore) GetDevices(_ context.Context, userID id.UserID) (map[id.DeviceID]*id.Device, error)

func (*MemoryStore) GetGroupSession

func (gs *MemoryStore) GetGroupSession(_ context.Context, roomID id.RoomID, senderKey id.SenderKey, sessionID id.SessionID) (*InboundGroupSession, error)

func (*MemoryStore) GetGroupSessionsForRoom

func (gs *MemoryStore) GetGroupSessionsForRoom(_ context.Context, roomID id.RoomID) dbutil.RowIter[*InboundGroupSession]

func (*MemoryStore) GetGroupSessionsWithoutKeyBackupVersion

func (gs *MemoryStore) GetGroupSessionsWithoutKeyBackupVersion(_ context.Context, version id.KeyBackupVersion) dbutil.RowIter[*InboundGroupSession]

func (*MemoryStore) GetLatestSession

func (gs *MemoryStore) GetLatestSession(_ context.Context, senderKey id.SenderKey) (*OlmSession, error)

func (*MemoryStore) GetOutboundGroupSession

func (gs *MemoryStore) GetOutboundGroupSession(_ context.Context, roomID id.RoomID) (*OutboundGroupSession, error)

func (*MemoryStore) GetOutdatedTrackedUsers

func (gs *MemoryStore) GetOutdatedTrackedUsers(_ context.Context) ([]id.UserID, error)

func (*MemoryStore) GetSecret

func (gs *MemoryStore) GetSecret(_ context.Context, name id.Secret) (value string, _ error)

func (*MemoryStore) GetSessions

func (gs *MemoryStore) GetSessions(_ context.Context, senderKey id.SenderKey) (OlmSessionList, error)

func (*MemoryStore) GetSignaturesForKeyBy

func (gs *MemoryStore) GetSignaturesForKeyBy(_ context.Context, userID id.UserID, key id.Ed25519, signerID id.UserID) (map[id.Ed25519]string, error)

func (*MemoryStore) GetWithheldGroupSession

func (gs *MemoryStore) GetWithheldGroupSession(_ context.Context, roomID id.RoomID, senderKey id.SenderKey, sessionID id.SessionID) (*event.RoomKeyWithheldEventContent, error)

func (*MemoryStore) HasSession

func (gs *MemoryStore) HasSession(_ context.Context, senderKey id.SenderKey) bool

func (*MemoryStore) IsKeySignedBy

func (gs *MemoryStore) IsKeySignedBy(ctx context.Context, userID id.UserID, key id.Ed25519, signerID id.UserID, signerKey id.Ed25519) (bool, error)

func (*MemoryStore) IsOutboundGroupSessionShared

func (gs *MemoryStore) IsOutboundGroupSessionShared(_ context.Context, userID id.UserID, identityKey id.IdentityKey, sessionID id.SessionID) (isShared bool, err error)

func (*MemoryStore) MarkOutboundGroupSessionShared

func (gs *MemoryStore) MarkOutboundGroupSessionShared(_ context.Context, userID id.UserID, identityKey id.IdentityKey, sessionID id.SessionID) error

func (*MemoryStore) MarkTrackedUsersOutdated

func (gs *MemoryStore) MarkTrackedUsersOutdated(_ context.Context, users []id.UserID) error

func (*MemoryStore) PutAccount

func (gs *MemoryStore) PutAccount(_ context.Context, account *OlmAccount) error

func (*MemoryStore) PutCrossSigningKey

func (gs *MemoryStore) PutCrossSigningKey(_ context.Context, userID id.UserID, usage id.CrossSigningUsage, key id.Ed25519) error

func (*MemoryStore) PutDevice

func (gs *MemoryStore) PutDevice(_ context.Context, userID id.UserID, device *id.Device) error

func (*MemoryStore) PutDevices

func (gs *MemoryStore) PutDevices(_ context.Context, userID id.UserID, devices map[id.DeviceID]*id.Device) error

func (*MemoryStore) PutGroupSession

func (gs *MemoryStore) PutGroupSession(_ context.Context, roomID id.RoomID, senderKey id.SenderKey, sessionID id.SessionID, igs *InboundGroupSession) error

func (*MemoryStore) PutSecret

func (gs *MemoryStore) PutSecret(_ context.Context, name id.Secret, value string) error

func (*MemoryStore) PutSignature

func (gs *MemoryStore) PutSignature(_ context.Context, signedUserID id.UserID, signedKey id.Ed25519, signerUserID id.UserID, signerKey id.Ed25519, signature string) error

func (*MemoryStore) PutWithheldGroupSession

func (gs *MemoryStore) PutWithheldGroupSession(_ context.Context, content event.RoomKeyWithheldEventContent) error

func (*MemoryStore) RedactExpiredGroupSessions

func (gs *MemoryStore) RedactExpiredGroupSessions(_ context.Context) ([]id.SessionID, error)

func (*MemoryStore) RedactGroupSession

func (gs *MemoryStore) RedactGroupSession(_ context.Context, roomID id.RoomID, senderKey id.SenderKey, sessionID id.SessionID, reason string) error

func (*MemoryStore) RedactGroupSessions

func (gs *MemoryStore) RedactGroupSessions(_ context.Context, roomID id.RoomID, senderKey id.SenderKey, reason string) ([]id.SessionID, error)

func (*MemoryStore) RedactOutdatedGroupSessions

func (gs *MemoryStore) RedactOutdatedGroupSessions(_ context.Context) ([]id.SessionID, error)

func (*MemoryStore) RemoveOutboundGroupSession

func (gs *MemoryStore) RemoveOutboundGroupSession(_ context.Context, roomID id.RoomID) error

func (*MemoryStore) UpdateOutboundGroupSession

func (gs *MemoryStore) UpdateOutboundGroupSession(_ context.Context, _ *OutboundGroupSession) error

func (*MemoryStore) UpdateSession

func (gs *MemoryStore) UpdateSession(_ context.Context, _ id.SenderKey, _ *OlmSession) error

func (*MemoryStore) ValidateMessageIndex

func (gs *MemoryStore) ValidateMessageIndex(_ context.Context, senderKey id.SenderKey, sessionID id.SessionID, eventID id.EventID, index uint, timestamp int64) (bool, error)

type OGSState

type OGSState int
const (
	OGSNotShared OGSState = iota
	OGSAlreadyShared
	OGSIgnored
)

type OlmAccount

type OlmAccount struct {
	Internal olm.Account

	Shared           bool
	KeyBackupVersion id.KeyBackupVersion
	// contains filtered or unexported fields
}

func NewOlmAccount

func NewOlmAccount() *OlmAccount

func (*OlmAccount) IdentityKey

func (account *OlmAccount) IdentityKey() id.IdentityKey

func (*OlmAccount) Keys

func (account *OlmAccount) Keys() (id.SigningKey, id.IdentityKey)

func (*OlmAccount) NewInboundSessionFrom

func (account *OlmAccount) NewInboundSessionFrom(senderKey id.Curve25519, ciphertext string) (*OlmSession, error)

func (*OlmAccount) SigningKey

func (account *OlmAccount) SigningKey() id.SigningKey

type OlmEventKeys

type OlmEventKeys struct {
	Ed25519 id.Ed25519 `json:"ed25519"`
}

type OlmMachine

type OlmMachine struct {
	Client *mautrix.Client
	SSSS   *ssss.Machine
	Log    *zerolog.Logger

	CryptoStore Store
	StateStore  StateStore

	PlaintextMentions bool

	// Never ask the server for keys automatically as a side effect during Megolm decryption.
	DisableDecryptKeyFetching bool

	// Don't mark outbound Olm sessions as shared for devices they were initially sent to.
	DisableSharedGroupSessionTracking bool

	SendKeysMinTrust  id.TrustState
	ShareKeysMinTrust id.TrustState

	AllowKeyShare func(context.Context, *id.Device, event.RequestedKeyInfo) *KeyShareRejection

	// Optional callback which is called when we save a session to store
	SessionReceived func(context.Context, id.SessionID)

	CrossSigningKeys *CrossSigningKeysCache

	DeleteOutboundKeysOnAck      bool
	DontStoreOutboundKeys        bool
	DeletePreviousKeysOnReceive  bool
	RatchetKeysOnDecrypt         bool
	DeleteFullyUsedKeysOnDecrypt bool
	DeleteKeysOnDeviceDelete     bool

	DisableDeviceChangeKeyRotation bool
	// contains filtered or unexported fields
}

OlmMachine is the main struct for handling Matrix end-to-end encryption.

func NewOlmMachine

func NewOlmMachine(client *mautrix.Client, log *zerolog.Logger, cryptoStore Store, stateStore StateStore) *OlmMachine

NewOlmMachine creates an OlmMachine with the given client, logger and stores.

func (*OlmMachine) AddAppserviceListener

func (mach *OlmMachine) AddAppserviceListener(ep asEventProcessor)

func (*OlmMachine) DecryptMegolmEvent

func (mach *OlmMachine) DecryptMegolmEvent(ctx context.Context, evt *event.Event) (*event.Event, error)

DecryptMegolmEvent decrypts an m.room.encrypted event where the algorithm is m.megolm.v1.aes-sha2

func (*OlmMachine) DownloadAndStoreLatestKeyBackup

func (mach *OlmMachine) DownloadAndStoreLatestKeyBackup(ctx context.Context, megolmBackupKey *backup.MegolmBackupKey) (id.KeyBackupVersion, error)

func (*OlmMachine) EncryptMegolmEvent

func (mach *OlmMachine) EncryptMegolmEvent(ctx context.Context, roomID id.RoomID, evtType event.Type, content interface{}) (*event.EncryptedEventContent, error)

EncryptMegolmEvent encrypts data with the m.megolm.v1.aes-sha2 algorithm.

If you use the event.Content struct, make sure you pass a pointer to the struct, as JSON serialization will not work correctly otherwise.

func (*OlmMachine) ExpiredKeyDeleteLoop

func (mach *OlmMachine) ExpiredKeyDeleteLoop(ctx context.Context)

func (*OlmMachine) ExportCrossSigningKeys

func (mach *OlmMachine) ExportCrossSigningKeys() CrossSigningSeeds

func (*OlmMachine) FetchCrossSigningKeysFromSSSS

func (mach *OlmMachine) FetchCrossSigningKeysFromSSSS(ctx context.Context, key *ssss.Key) error

FetchCrossSigningKeysFromSSSS fetches all the cross-signing keys from SSSS, decrypts them using the given key and stores them in the olm machine.

func (*OlmMachine) FetchKeys

func (mach *OlmMachine) FetchKeys(ctx context.Context, users []id.UserID, includeUntracked bool) (data map[id.UserID]map[id.DeviceID]*id.Device, err error)

func (*OlmMachine) Fingerprint

func (mach *OlmMachine) Fingerprint() string

Fingerprint returns the fingerprint of the Olm account that can be used for non-interactive verification.

func (*OlmMachine) FlushStore

func (mach *OlmMachine) FlushStore(ctx context.Context) error

FlushStore calls the Flush method of the CryptoStore.

func (*OlmMachine) GenerateAndUploadCrossSigningKeys

func (mach *OlmMachine) GenerateAndUploadCrossSigningKeys(ctx context.Context, uiaCallback mautrix.UIACallback, passphrase string) (string, *CrossSigningKeysCache, error)

GenerateAndUploadCrossSigningKeys generates a new key with all corresponding cross-signing keys.

A passphrase can be provided to generate the SSSS key. If the passphrase is empty, a random key is used. The base58-formatted recovery key is the first return parameter.

The account password of the user is required for uploading keys to the server.

func (*OlmMachine) GenerateAndUploadCrossSigningKeysWithPassword

func (mach *OlmMachine) GenerateAndUploadCrossSigningKeysWithPassword(ctx context.Context, userPassword, passphrase string) (string, *CrossSigningKeysCache, error)

func (*OlmMachine) GenerateCrossSigningKeys

func (mach *OlmMachine) GenerateCrossSigningKeys() (*CrossSigningKeysCache, error)

GenerateCrossSigningKeys generates new cross-signing keys.

func (*OlmMachine) GetAccount

func (mach *OlmMachine) GetAccount() *OlmAccount

func (*OlmMachine) GetAndStoreKeyBackup

func (mach *OlmMachine) GetAndStoreKeyBackup(ctx context.Context, version id.KeyBackupVersion, megolmBackupKey *backup.MegolmBackupKey) error

func (*OlmMachine) GetAndVerifyLatestKeyBackupVersion

func (mach *OlmMachine) GetAndVerifyLatestKeyBackupVersion(ctx context.Context) (*mautrix.RespRoomKeysVersion[backup.MegolmAuthData], error)

func (*OlmMachine) GetCrossSigningPublicKeys

func (mach *OlmMachine) GetCrossSigningPublicKeys(ctx context.Context, userID id.UserID) (*CrossSigningPublicKeysCache, error)

func (*OlmMachine) GetOrFetchDevice

func (mach *OlmMachine) GetOrFetchDevice(ctx context.Context, userID id.UserID, deviceID id.DeviceID) (*id.Device, error)

GetOrFetchDevice attempts to retrieve the device identity for the given device from the store and if it's not found it asks the server for it.

func (*OlmMachine) GetOrFetchDeviceByKey

func (mach *OlmMachine) GetOrFetchDeviceByKey(ctx context.Context, userID id.UserID, identityKey id.IdentityKey) (*id.Device, error)

GetOrFetchDeviceByKey attempts to retrieve the device identity for the device with the given identity key from the store and if it's not found it asks the server for it. This returns nil if the server doesn't return a device with the given identity key.

func (*OlmMachine) GetOrRequestSecret

func (mach *OlmMachine) GetOrRequestSecret(ctx context.Context, name id.Secret, receiver SecretReceiverFunc, timeout time.Duration) (err error)

func (*OlmMachine) GetOwnCrossSigningPublicKeys

func (mach *OlmMachine) GetOwnCrossSigningPublicKeys(ctx context.Context) *CrossSigningPublicKeysCache

func (*OlmMachine) HandleBeeperRoomKeyAck

func (mach *OlmMachine) HandleBeeperRoomKeyAck(ctx context.Context, sender id.UserID, content *event.BeeperRoomKeyAckEventContent)

func (*OlmMachine) HandleDeviceLists

func (mach *OlmMachine) HandleDeviceLists(ctx context.Context, dl *mautrix.DeviceLists, since string)

func (*OlmMachine) HandleEncryptedEvent

func (mach *OlmMachine) HandleEncryptedEvent(ctx context.Context, evt *event.Event)

func (*OlmMachine) HandleMemberEvent

func (mach *OlmMachine) HandleMemberEvent(ctx context.Context, evt *event.Event)

HandleMemberEvent handles a single membership event.

Currently this is not automatically called, so you must add a listener yourself:

client.Syncer.(mautrix.ExtensibleSyncer).OnEventType(event.StateMember, c.crypto.HandleMemberEvent)

func (*OlmMachine) HandleOTKCounts

func (mach *OlmMachine) HandleOTKCounts(ctx context.Context, otkCount *mautrix.OTKCount)

func (*OlmMachine) HandleRoomKeyRequest

func (mach *OlmMachine) HandleRoomKeyRequest(ctx context.Context, sender id.UserID, content *event.RoomKeyRequestEventContent)

func (*OlmMachine) HandleRoomKeyWithheld

func (mach *OlmMachine) HandleRoomKeyWithheld(ctx context.Context, content *event.RoomKeyWithheldEventContent)

func (*OlmMachine) HandleSecretRequest

func (mach *OlmMachine) HandleSecretRequest(ctx context.Context, userID id.UserID, content *event.SecretRequestEventContent)

func (*OlmMachine) HandleToDeviceEvent

func (mach *OlmMachine) HandleToDeviceEvent(ctx context.Context, evt *event.Event)

HandleToDeviceEvent handles a single to-device event. This is automatically called by ProcessSyncResponse, so you don't need to add any custom handlers if you use that method.

func (*OlmMachine) ImportCrossSigningKeys

func (mach *OlmMachine) ImportCrossSigningKeys(keys CrossSigningSeeds) (err error)

func (*OlmMachine) ImportKeys

func (mach *OlmMachine) ImportKeys(ctx context.Context, passphrase string, data []byte) (int, int, error)

ImportKeys imports data that was exported with the format specified in the Matrix spec. See https://spec.matrix.org/v1.2/client-server-api/#key-exports

func (*OlmMachine) ImportRoomKeyFromBackup

func (mach *OlmMachine) ImportRoomKeyFromBackup(ctx context.Context, version id.KeyBackupVersion, roomID id.RoomID, sessionID id.SessionID, keyBackupData *backup.MegolmSessionData) error

func (*OlmMachine) IsDeviceTrusted

func (mach *OlmMachine) IsDeviceTrusted(device *id.Device) bool

IsDeviceTrusted returns whether a device has been determined to be trusted either through verification or cross-signing.

func (*OlmMachine) IsUserTrusted

func (mach *OlmMachine) IsUserTrusted(ctx context.Context, userID id.UserID) (bool, error)

IsUserTrusted returns whether a user has been determined to be trusted by our user-signing key having signed their master key. In the case the user ID is our own and we have successfully retrieved our cross-signing keys, we trust our own user.

func (*OlmMachine) KeyBackupVersion

func (mach *OlmMachine) KeyBackupVersion() id.KeyBackupVersion

func (*OlmMachine) Load

func (mach *OlmMachine) Load(ctx context.Context) (err error)

Load loads the Olm account information from the crypto store. If there's no olm account, a new one is created. This must be called before using the machine.

func (*OlmMachine) LoadDevices

func (mach *OlmMachine) LoadDevices(ctx context.Context, user id.UserID) (keys map[id.DeviceID]*id.Device)

func (*OlmMachine) OnDevicesChanged

func (mach *OlmMachine) OnDevicesChanged(ctx context.Context, userID id.UserID)

OnDevicesChanged finds all shared rooms with the given user and invalidates outbound sessions in those rooms.

This is called automatically whenever a device list change is noticed in ProcessSyncResponse and usually does not need to be called manually.

func (*OlmMachine) OwnIdentity

func (mach *OlmMachine) OwnIdentity() *id.Device

OwnIdentity returns this device's id.Device struct

func (*OlmMachine) ProcessSyncResponse

func (mach *OlmMachine) ProcessSyncResponse(ctx context.Context, resp *mautrix.RespSync, since string) bool

ProcessSyncResponse processes a single /sync response.

This can be easily registered into a mautrix client using .OnSync():

client.Syncer.(mautrix.ExtensibleSyncer).OnSync(c.crypto.ProcessSyncResponse)

func (*OlmMachine) PublishCrossSigningKeys

func (mach *OlmMachine) PublishCrossSigningKeys(ctx context.Context, keys *CrossSigningKeysCache, uiaCallback mautrix.UIACallback) error

PublishCrossSigningKeys signs and uploads the public keys of the given cross-signing keys to the server.

func (*OlmMachine) RequestRoomKey deprecated

func (mach *OlmMachine) RequestRoomKey(ctx context.Context, toUser id.UserID, toDevice id.DeviceID,
	roomID id.RoomID, senderKey id.SenderKey, sessionID id.SessionID) (chan bool, error)

RequestRoomKey sends a key request for a room to the current user's devices. If the context is cancelled, then so is the key request. Returns a bool channel that will get notified either when the key is received or the request is cancelled.

Deprecated: this only supports a single key request target, so the whole automatic cancelling feature isn't very useful.

func (*OlmMachine) ResolveTrust

func (mach *OlmMachine) ResolveTrust(device *id.Device) id.TrustState

func (*OlmMachine) ResolveTrustContext

func (mach *OlmMachine) ResolveTrustContext(ctx context.Context, device *id.Device) (id.TrustState, error)

ResolveTrustContext resolves the trust state of the device from cross-signing.

func (*OlmMachine) SendEncryptedToDevice

func (mach *OlmMachine) SendEncryptedToDevice(ctx context.Context, device *id.Device, evtType event.Type, content event.Content) error

SendEncryptedToDevice sends an Olm-encrypted event to the given user device.

func (*OlmMachine) SendRoomKeyRequest

func (mach *OlmMachine) SendRoomKeyRequest(ctx context.Context, roomID id.RoomID, senderKey id.SenderKey, sessionID id.SessionID, requestID string, users map[id.UserID][]id.DeviceID) error

SendRoomKeyRequest sends a key request for the given key (identified by the room ID, sender key and session ID) to the given users.

The request ID parameter is optional. If it's empty, a random ID will be generated.

This function does not wait for the keys to arrive. You can use WaitForSession to wait for the session to arrive (in any way, not just as a reply to this request). There's also RequestRoomKey which waits for a response to the specific key request, but currently it only supports a single target device and is therefore deprecated. A future function may properly support multiple targets and automatically canceling the other requests when receiving the first response.

func (*OlmMachine) SetKeyBackupVersion

func (mach *OlmMachine) SetKeyBackupVersion(ctx context.Context, version id.KeyBackupVersion) error

func (*OlmMachine) ShareGroupSession

func (mach *OlmMachine) ShareGroupSession(ctx context.Context, roomID id.RoomID, users []id.UserID) error

ShareGroupSession shares a group session for a specific room with all the devices of the given user list.

For devices with TrustStateBlacklisted, a m.room_key.withheld event with code=m.blacklisted is sent. If AllowUnverifiedDevices is false, a similar event with code=m.unverified is sent to devices with TrustStateUnset

func (*OlmMachine) ShareKeys

func (mach *OlmMachine) ShareKeys(ctx context.Context, currentOTKCount int) error

ShareKeys uploads necessary keys to the server.

If the Olm account hasn't been shared, the account keys will be uploaded. If currentOTKCount is less than half of the limit (100 / 2 = 50), enough one-time keys will be uploaded so exactly half of the limit is filled.

func (*OlmMachine) SignOwnDevice

func (mach *OlmMachine) SignOwnDevice(ctx context.Context, device *id.Device) error

SignOwnDevice creates a cross-signing signature for a device belonging to the current user and uploads it to the server.

func (*OlmMachine) SignOwnMasterKey

func (mach *OlmMachine) SignOwnMasterKey(ctx context.Context) error

SignOwnMasterKey uses the current account for signing the current user's master key and uploads the signature.

func (*OlmMachine) SignUser

func (mach *OlmMachine) SignUser(ctx context.Context, userID id.UserID, masterKey id.Ed25519) error

SignUser creates a cross-signing signature for a user, stores it and uploads it to the server.

func (*OlmMachine) UploadCrossSigningKeysToSSSS

func (mach *OlmMachine) UploadCrossSigningKeysToSSSS(ctx context.Context, key *ssss.Key, keys *CrossSigningKeysCache) error

UploadCrossSigningKeysToSSSS stores the given cross-signing keys on the server encrypted with the given key.

func (*OlmMachine) WaitForSession

func (mach *OlmMachine) WaitForSession(ctx context.Context, roomID id.RoomID, senderKey id.SenderKey, sessionID id.SessionID, timeout time.Duration) bool

WaitForSession waits for the given Megolm session to arrive.

type OlmSession

type OlmSession struct {
	Internal olm.Session
	ExpirationMixin
	// contains filtered or unexported fields
}

func (*OlmSession) Decrypt

func (session *OlmSession) Decrypt(ciphertext string, msgType id.OlmMsgType) ([]byte, error)

func (*OlmSession) Describe

func (session *OlmSession) Describe() string

func (*OlmSession) Encrypt

func (session *OlmSession) Encrypt(plaintext []byte) (id.OlmMsgType, []byte)

func (*OlmSession) ID

func (session *OlmSession) ID() id.SessionID

type OlmSessionList

type OlmSessionList []*OlmSession

OlmSessionList is a list of OlmSessions. It implements sort.Interface so that the session with recent successful decryptions comes first.

func (OlmSessionList) Len

func (o OlmSessionList) Len() int

func (OlmSessionList) Less

func (o OlmSessionList) Less(i, j int) bool

func (OlmSessionList) Swap

func (o OlmSessionList) Swap(i, j int)

type OutboundGroupSession

type OutboundGroupSession struct {
	Internal olm.OutboundGroupSession

	ExpirationMixin
	MaxMessages  int
	MessageCount int

	Users  map[UserDevice]OGSState
	RoomID id.RoomID
	Shared bool
	// contains filtered or unexported fields
}

func NewOutboundGroupSession

func NewOutboundGroupSession(roomID id.RoomID, encryptionContent *event.EncryptionEventContent) *OutboundGroupSession

func (*OutboundGroupSession) Encrypt

func (ogs *OutboundGroupSession) Encrypt(plaintext []byte) ([]byte, error)

func (*OutboundGroupSession) Expired

func (ogs *OutboundGroupSession) Expired() bool

func (*OutboundGroupSession) ID

func (ogs *OutboundGroupSession) ID() id.SessionID

func (*OutboundGroupSession) ShareContent

func (ogs *OutboundGroupSession) ShareContent() event.Content

type RatchetSafety

type RatchetSafety struct {
	NextIndex     uint   `json:"next_index"`
	MissedIndices []uint `json:"missed_indices,omitempty"`
	LostIndices   []uint `json:"lost_indices,omitempty"`
}

type SQLCryptoStore

type SQLCryptoStore struct {
	DB *dbutil.Database

	AccountID string
	DeviceID  id.DeviceID
	SyncToken string
	PickleKey []byte
	Account   *OlmAccount
	// contains filtered or unexported fields
}

SQLCryptoStore is an implementation of a crypto Store for a database backend.

func NewSQLCryptoStore

func NewSQLCryptoStore(db *dbutil.Database, log dbutil.DatabaseLogger, accountID string, deviceID id.DeviceID, pickleKey []byte) *SQLCryptoStore

NewSQLCryptoStore initializes a new crypto Store using the given database, for a device's crypto material. The stored material will be encrypted with the given key.

func (*SQLCryptoStore) AddOutboundGroupSession

func (store *SQLCryptoStore) AddOutboundGroupSession(ctx context.Context, session *OutboundGroupSession) error

AddOutboundGroupSession stores an outbound Megolm session, along with the information about the room and involved devices.

func (*SQLCryptoStore) AddSession

func (store *SQLCryptoStore) AddSession(ctx context.Context, key id.SenderKey, session *OlmSession) error

AddSession persists an Olm session for a sender in the database.

func (*SQLCryptoStore) DeleteSecret

func (store *SQLCryptoStore) DeleteSecret(ctx context.Context, name id.Secret) (err error)

func (*SQLCryptoStore) DropSignaturesByKey

func (store *SQLCryptoStore) DropSignaturesByKey(ctx context.Context, userID id.UserID, key id.Ed25519) (int64, error)

DropSignaturesByKey deletes the signatures made by the given user and key from the store. It returns the number of signatures deleted.

func (*SQLCryptoStore) FilterTrackedUsers

func (store *SQLCryptoStore) FilterTrackedUsers(ctx context.Context, users []id.UserID) ([]id.UserID, error)

FilterTrackedUsers finds all the user IDs out of the given ones for which the database contains identity information.

func (*SQLCryptoStore) FindDeviceByKey

func (store *SQLCryptoStore) FindDeviceByKey(ctx context.Context, userID id.UserID, identityKey id.IdentityKey) (*id.Device, error)

FindDeviceByKey finds a specific device by its sender key.

func (*SQLCryptoStore) FindDeviceID

func (store *SQLCryptoStore) FindDeviceID(ctx context.Context) (deviceID id.DeviceID, err error)

func (*SQLCryptoStore) Flush

func (store *SQLCryptoStore) Flush(_ context.Context) error

Flush does nothing for this implementation as data is already persisted in the database.

func (*SQLCryptoStore) GetAccount

func (store *SQLCryptoStore) GetAccount(ctx context.Context) (*OlmAccount, error)

GetAccount retrieves an OlmAccount from the database.

func (*SQLCryptoStore) GetAllGroupSessions

func (store *SQLCryptoStore) GetAllGroupSessions(ctx context.Context) dbutil.RowIter[*InboundGroupSession]

func (*SQLCryptoStore) GetCrossSigningKeys

func (store *SQLCryptoStore) GetCrossSigningKeys(ctx context.Context, userID id.UserID) (map[id.CrossSigningUsage]id.CrossSigningKey, error)

GetCrossSigningKeys retrieves a user's stored cross-signing keys.

func (*SQLCryptoStore) GetDevice

func (store *SQLCryptoStore) GetDevice(ctx context.Context, userID id.UserID, deviceID id.DeviceID) (*id.Device, error)

GetDevice returns the device dentity for a given user and device ID.

func (*SQLCryptoStore) GetDevices

func (store *SQLCryptoStore) GetDevices(ctx context.Context, userID id.UserID) (map[id.DeviceID]*id.Device, error)

GetDevices returns a map of device IDs to device identities, including the identity and signing keys, for a given user ID.

func (*SQLCryptoStore) GetGroupSession

func (store *SQLCryptoStore) GetGroupSession(ctx context.Context, roomID id.RoomID, senderKey id.SenderKey, sessionID id.SessionID) (*InboundGroupSession, error)

GetGroupSession retrieves an inbound Megolm group session for a room, sender and session.

func (*SQLCryptoStore) GetGroupSessionsForRoom

func (store *SQLCryptoStore) GetGroupSessionsForRoom(ctx context.Context, roomID id.RoomID) dbutil.RowIter[*InboundGroupSession]

func (*SQLCryptoStore) GetGroupSessionsWithoutKeyBackupVersion

func (store *SQLCryptoStore) GetGroupSessionsWithoutKeyBackupVersion(ctx context.Context, version id.KeyBackupVersion) dbutil.RowIter[*InboundGroupSession]

func (*SQLCryptoStore) GetLatestSession

func (store *SQLCryptoStore) GetLatestSession(ctx context.Context, key id.SenderKey) (*OlmSession, error)

GetLatestSession retrieves the Olm session for a given sender key from the database that has the largest ID.

func (*SQLCryptoStore) GetNextBatch

func (store *SQLCryptoStore) GetNextBatch(ctx context.Context) (string, error)

GetNextBatch retrieves the next sync batch token for the current account.

func (*SQLCryptoStore) GetOutboundGroupSession

func (store *SQLCryptoStore) GetOutboundGroupSession(ctx context.Context, roomID id.RoomID) (*OutboundGroupSession, error)

GetOutboundGroupSession retrieves the outbound Megolm session for the given room ID.

func (*SQLCryptoStore) GetOutdatedTrackedUsers

func (store *SQLCryptoStore) GetOutdatedTrackedUsers(ctx context.Context) ([]id.UserID, error)

GetOutdatedTrackerUsers gets all tracked users whose devices need to be updated.

func (*SQLCryptoStore) GetSecret

func (store *SQLCryptoStore) GetSecret(ctx context.Context, name id.Secret) (value string, err error)

func (*SQLCryptoStore) GetSessions

func (store *SQLCryptoStore) GetSessions(ctx context.Context, key id.SenderKey) (OlmSessionList, error)

GetSessions returns all the known Olm sessions for a sender key.

func (*SQLCryptoStore) GetSignaturesForKeyBy

func (store *SQLCryptoStore) GetSignaturesForKeyBy(ctx context.Context, userID id.UserID, key id.Ed25519, signerID id.UserID) (map[id.Ed25519]string, error)

GetSignaturesForKeyBy retrieves the stored signatures for a given cross-signing or device key, by the given signer.

func (*SQLCryptoStore) GetWithheldGroupSession

func (store *SQLCryptoStore) GetWithheldGroupSession(ctx context.Context, roomID id.RoomID, senderKey id.SenderKey, sessionID id.SessionID) (*event.RoomKeyWithheldEventContent, error)

func (*SQLCryptoStore) HasSession

func (store *SQLCryptoStore) HasSession(ctx context.Context, key id.SenderKey) bool

HasSession returns whether there is an Olm session for the given sender key.

func (*SQLCryptoStore) IsKeySignedBy

func (store *SQLCryptoStore) IsKeySignedBy(ctx context.Context, signedUserID id.UserID, signedKey id.Ed25519, signerUserID id.UserID, signerKey id.Ed25519) (isSigned bool, err error)

IsKeySignedBy returns whether a cross-signing or device key is signed by the given signer.

func (*SQLCryptoStore) IsOutboundGroupSessionShared

func (store *SQLCryptoStore) IsOutboundGroupSessionShared(ctx context.Context, userID id.UserID, identityKey id.IdentityKey, sessionID id.SessionID) (shared bool, err error)

func (*SQLCryptoStore) LoadFilterID

func (store *SQLCryptoStore) LoadFilterID(ctx context.Context, _ id.UserID) (string, error)

func (*SQLCryptoStore) LoadNextBatch

func (store *SQLCryptoStore) LoadNextBatch(ctx context.Context, _ id.UserID) (string, error)

func (*SQLCryptoStore) MarkOutboundGroupSessionShared

func (store *SQLCryptoStore) MarkOutboundGroupSessionShared(ctx context.Context, userID id.UserID, identityKey id.IdentityKey, sessionID id.SessionID) error

func (*SQLCryptoStore) MarkTrackedUsersOutdated

func (store *SQLCryptoStore) MarkTrackedUsersOutdated(ctx context.Context, users []id.UserID) error

MarkTrackedUsersOutdated flags that the device list for given users are outdated.

func (*SQLCryptoStore) PutAccount

func (store *SQLCryptoStore) PutAccount(ctx context.Context, account *OlmAccount) error

PutAccount stores an OlmAccount in the database.

func (*SQLCryptoStore) PutCrossSigningKey

func (store *SQLCryptoStore) PutCrossSigningKey(ctx context.Context, userID id.UserID, usage id.CrossSigningUsage, key id.Ed25519) error

PutCrossSigningKey stores a cross-signing key of some user along with its usage.

func (*SQLCryptoStore) PutDevice

func (store *SQLCryptoStore) PutDevice(ctx context.Context, userID id.UserID, device *id.Device) error

PutDevice stores a single device for a user, replacing it if it exists already.

func (*SQLCryptoStore) PutDevices

func (store *SQLCryptoStore) PutDevices(ctx context.Context, userID id.UserID, devices map[id.DeviceID]*id.Device) error

PutDevices stores the device identity information for the given user ID.

func (*SQLCryptoStore) PutGroupSession

func (store *SQLCryptoStore) PutGroupSession(ctx context.Context, roomID id.RoomID, senderKey id.SenderKey, sessionID id.SessionID, session *InboundGroupSession) error

PutGroupSession stores an inbound Megolm group session for a room, sender and session.

func (*SQLCryptoStore) PutNextBatch

func (store *SQLCryptoStore) PutNextBatch(ctx context.Context, nextBatch string) error

PutNextBatch stores the next sync batch token for the current account.

func (*SQLCryptoStore) PutSecret

func (store *SQLCryptoStore) PutSecret(ctx context.Context, name id.Secret, value string) error

func (*SQLCryptoStore) PutSignature

func (store *SQLCryptoStore) PutSignature(ctx context.Context, signedUserID id.UserID, signedKey id.Ed25519, signerUserID id.UserID, signerKey id.Ed25519, signature string) error

PutSignature stores a signature of a cross-signing or device key along with the signer's user ID and key.

func (*SQLCryptoStore) PutWithheldGroupSession

func (store *SQLCryptoStore) PutWithheldGroupSession(ctx context.Context, content event.RoomKeyWithheldEventContent) error

func (*SQLCryptoStore) RedactExpiredGroupSessions

func (store *SQLCryptoStore) RedactExpiredGroupSessions(ctx context.Context) ([]id.SessionID, error)

func (*SQLCryptoStore) RedactGroupSession

func (store *SQLCryptoStore) RedactGroupSession(ctx context.Context, _ id.RoomID, _ id.SenderKey, sessionID id.SessionID, reason string) error

func (*SQLCryptoStore) RedactGroupSessions

func (store *SQLCryptoStore) RedactGroupSessions(ctx context.Context, roomID id.RoomID, senderKey id.SenderKey, reason string) ([]id.SessionID, error)

func (*SQLCryptoStore) RedactOutdatedGroupSessions

func (store *SQLCryptoStore) RedactOutdatedGroupSessions(ctx context.Context) ([]id.SessionID, error)

func (*SQLCryptoStore) RemoveOutboundGroupSession

func (store *SQLCryptoStore) RemoveOutboundGroupSession(ctx context.Context, roomID id.RoomID) error

RemoveOutboundGroupSession removes the outbound Megolm session for the given room ID.

func (*SQLCryptoStore) SaveFilterID

func (store *SQLCryptoStore) SaveFilterID(ctx context.Context, _ id.UserID, _ string) error

func (*SQLCryptoStore) SaveNextBatch

func (store *SQLCryptoStore) SaveNextBatch(ctx context.Context, _ id.UserID, nextBatchToken string) error

func (*SQLCryptoStore) UpdateOutboundGroupSession

func (store *SQLCryptoStore) UpdateOutboundGroupSession(ctx context.Context, session *OutboundGroupSession) error

UpdateOutboundGroupSession replaces an outbound Megolm session with for same room and session ID.

func (*SQLCryptoStore) UpdateSession

func (store *SQLCryptoStore) UpdateSession(ctx context.Context, _ id.SenderKey, session *OlmSession) error

UpdateSession replaces the Olm session for a sender in the database.

func (*SQLCryptoStore) ValidateMessageIndex

func (store *SQLCryptoStore) ValidateMessageIndex(ctx context.Context, senderKey id.SenderKey, sessionID id.SessionID, eventID id.EventID, index uint, timestamp int64) (bool, error)

ValidateMessageIndex returns whether the given event information match the ones stored in the database for the given sender key, session ID and index. If the index hasn't been stored, this will store it.

type SecretReceiverFunc

type SecretReceiverFunc func(string) (bool, error)

Callback function to process a received secret.

Returning true or an error will immediately return from the wait loop, returning false will continue waiting for new responses.

type SenderClaimedKeys

type SenderClaimedKeys struct {
	Ed25519 id.Ed25519 `json:"ed25519"`
}

type StateStore

type StateStore interface {
	// IsEncrypted returns whether a room is encrypted.
	IsEncrypted(context.Context, id.RoomID) (bool, error)
	// GetEncryptionEvent returns the encryption event's content for an encrypted room.
	GetEncryptionEvent(context.Context, id.RoomID) (*event.EncryptionEventContent, error)
	// FindSharedRooms returns the encrypted rooms that another user is also in for a user ID.
	FindSharedRooms(context.Context, id.UserID) ([]id.RoomID, error)
}

StateStore is used by OlmMachine to get room state information that's needed for encryption.

type Store

type Store interface {
	// Flush ensures that everything in the store is persisted to disk.
	// This doesn't have to do anything, e.g. for database-backed implementations that persist everything immediately.
	Flush(context.Context) error

	// PutAccount updates the OlmAccount in the store.
	PutAccount(context.Context, *OlmAccount) error
	// GetAccount returns the OlmAccount in the store that was previously inserted with PutAccount.
	GetAccount(ctx context.Context) (*OlmAccount, error)

	// AddSession inserts an Olm session into the store.
	AddSession(context.Context, id.SenderKey, *OlmSession) error
	// HasSession returns whether or not the store has an Olm session with the given sender key.
	HasSession(context.Context, id.SenderKey) bool
	// GetSessions returns all Olm sessions in the store with the given sender key.
	GetSessions(context.Context, id.SenderKey) (OlmSessionList, error)
	// GetLatestSession returns the session with the highest session ID (lexiographically sorting).
	// It's usually safe to return the most recently added session if sorting by session ID is too difficult.
	GetLatestSession(context.Context, id.SenderKey) (*OlmSession, error)
	// UpdateSession updates a session that has previously been inserted with AddSession.
	UpdateSession(context.Context, id.SenderKey, *OlmSession) error

	// PutGroupSession inserts an inbound Megolm session into the store. If an earlier withhold event has been inserted
	// with PutWithheldGroupSession, this call should replace that. However, PutWithheldGroupSession must not replace
	// sessions inserted with this call.
	PutGroupSession(context.Context, id.RoomID, id.SenderKey, id.SessionID, *InboundGroupSession) error
	// GetGroupSession gets an inbound Megolm session from the store. If the group session has been withheld
	// (i.e. a room key withheld event has been saved with PutWithheldGroupSession), this should return the
	// ErrGroupSessionWithheld error. The caller may use GetWithheldGroupSession to find more details.
	GetGroupSession(context.Context, id.RoomID, id.SenderKey, id.SessionID) (*InboundGroupSession, error)
	// RedactGroupSession removes the session data for the given inbound Megolm session from the store.
	RedactGroupSession(context.Context, id.RoomID, id.SenderKey, id.SessionID, string) error
	// RedactGroupSessions removes the session data for all inbound Megolm sessions from a specific device and/or in a specific room.
	RedactGroupSessions(context.Context, id.RoomID, id.SenderKey, string) ([]id.SessionID, error)
	// RedactExpiredGroupSessions removes the session data for all inbound Megolm sessions that have expired.
	RedactExpiredGroupSessions(context.Context) ([]id.SessionID, error)
	// RedactOutdatedGroupSessions removes the session data for all inbound Megolm sessions that are lacking the expiration metadata.
	RedactOutdatedGroupSessions(context.Context) ([]id.SessionID, error)
	// PutWithheldGroupSession tells the store that a specific Megolm session was withheld.
	PutWithheldGroupSession(context.Context, event.RoomKeyWithheldEventContent) error
	// GetWithheldGroupSession gets the event content that was previously inserted with PutWithheldGroupSession.
	GetWithheldGroupSession(context.Context, id.RoomID, id.SenderKey, id.SessionID) (*event.RoomKeyWithheldEventContent, error)

	// GetGroupSessionsForRoom gets all the inbound Megolm sessions for a specific room. This is used for creating key
	// export files. Unlike GetGroupSession, this should not return any errors about withheld keys.
	GetGroupSessionsForRoom(context.Context, id.RoomID) dbutil.RowIter[*InboundGroupSession]
	// GetAllGroupSessions gets all the inbound Megolm sessions in the store. This is used for creating key export
	// files. Unlike GetGroupSession, this should not return any errors about withheld keys.
	GetAllGroupSessions(context.Context) dbutil.RowIter[*InboundGroupSession]
	// GetGroupSessionsWithoutKeyBackupVersion gets all the inbound Megolm sessions in the store that do not match given key backup version.
	GetGroupSessionsWithoutKeyBackupVersion(context.Context, id.KeyBackupVersion) dbutil.RowIter[*InboundGroupSession]

	// AddOutboundGroupSession inserts the given outbound Megolm session into the store.
	//
	// The store should index inserted sessions by the RoomID field to support getting and removing sessions.
	// There will only be one outbound session per room ID at a time.
	AddOutboundGroupSession(context.Context, *OutboundGroupSession) error
	// UpdateOutboundGroupSession updates the given outbound Megolm session in the store.
	UpdateOutboundGroupSession(context.Context, *OutboundGroupSession) error
	// GetOutboundGroupSession gets the stored outbound Megolm session for the given room ID from the store.
	GetOutboundGroupSession(context.Context, id.RoomID) (*OutboundGroupSession, error)
	// RemoveOutboundGroupSession removes the stored outbound Megolm session for the given room ID.
	RemoveOutboundGroupSession(context.Context, id.RoomID) error
	// MarkOutboutGroupSessionShared flags that the currently known device has been shared the keys for the specified session.
	MarkOutboundGroupSessionShared(context.Context, id.UserID, id.IdentityKey, id.SessionID) error
	// IsOutboutGroupSessionShared checks if the specified session has been shared with the device.
	IsOutboundGroupSessionShared(context.Context, id.UserID, id.IdentityKey, id.SessionID) (bool, error)

	// ValidateMessageIndex validates that the given message details aren't from a replay attack.
	//
	// Implementations should store a map from (senderKey, sessionID, index) to (eventID, timestamp), then use that map
	// to check whether or not the message index is valid:
	//
	// * If the map key doesn't exist, the given values should be stored and this should return true.
	// * If the map key exists and the stored values match the given values, this should return true.
	// * If the map key exists, but the stored values do not match the given values, this should return false.
	ValidateMessageIndex(ctx context.Context, senderKey id.SenderKey, sessionID id.SessionID, eventID id.EventID, index uint, timestamp int64) (bool, error)

	// GetDevices returns a map from device ID to id.Device struct containing all devices of a given user.
	GetDevices(context.Context, id.UserID) (map[id.DeviceID]*id.Device, error)
	// GetDevice returns a specific device of a given user.
	GetDevice(context.Context, id.UserID, id.DeviceID) (*id.Device, error)
	// PutDevice stores a single device for a user, replacing it if it exists already.
	PutDevice(context.Context, id.UserID, *id.Device) error
	// PutDevices overrides the stored device list for the given user with the given list.
	PutDevices(context.Context, id.UserID, map[id.DeviceID]*id.Device) error
	// FindDeviceByKey finds a specific device by its identity key.
	FindDeviceByKey(context.Context, id.UserID, id.IdentityKey) (*id.Device, error)
	// FilterTrackedUsers returns a filtered version of the given list that only includes user IDs whose device lists
	// have been stored with PutDevices. A user is considered tracked even if the PutDevices list was empty.
	FilterTrackedUsers(context.Context, []id.UserID) ([]id.UserID, error)
	// MarkTrackedUsersOutdated flags that the device list for given users are outdated.
	MarkTrackedUsersOutdated(context.Context, []id.UserID) error
	// GetOutdatedTrackerUsers gets all tracked users whose devices need to be updated.
	GetOutdatedTrackedUsers(context.Context) ([]id.UserID, error)

	// PutCrossSigningKey stores a cross-signing key of some user along with its usage.
	PutCrossSigningKey(context.Context, id.UserID, id.CrossSigningUsage, id.Ed25519) error
	// GetCrossSigningKeys retrieves a user's stored cross-signing keys.
	GetCrossSigningKeys(context.Context, id.UserID) (map[id.CrossSigningUsage]id.CrossSigningKey, error)
	// PutSignature stores a signature of a cross-signing or device key along with the signer's user ID and key.
	PutSignature(ctx context.Context, signedUser id.UserID, signedKey id.Ed25519, signerUser id.UserID, signerKey id.Ed25519, signature string) error
	// IsKeySignedBy returns whether a cross-signing or device key is signed by the given signer.
	IsKeySignedBy(ctx context.Context, userID id.UserID, key id.Ed25519, signedByUser id.UserID, signedByKey id.Ed25519) (bool, error)
	// DropSignaturesByKey deletes the signatures made by the given user and key from the store. It returns the number of signatures deleted.
	DropSignaturesByKey(context.Context, id.UserID, id.Ed25519) (int64, error)

	// PutSecret stores a named secret, replacing it if it exists already.
	PutSecret(context.Context, id.Secret, string) error
	// GetSecret returns a named secret.
	GetSecret(context.Context, id.Secret) (string, error)
	// DeleteSecret removes a named secret.
	DeleteSecret(context.Context, id.Secret) error
}

Store is used by OlmMachine to store Olm and Megolm sessions, user device lists and message indices.

General implementation details: * Get methods should not return errors if the requested data does not exist in the store, they should simply return nil. * Update methods may assume that the pointer is the same as what has earlier been added to or fetched from the store.

type TimeMixin

type TimeMixin struct {
	CreationTime      time.Time
	LastEncryptedTime time.Time
	LastDecryptedTime time.Time
}

type UserDevice

type UserDevice struct {
	UserID   id.UserID
	DeviceID id.DeviceID
}

Directories

Path Synopsis
Package goolm is a pure Go implementation of libolm.
Package goolm is a pure Go implementation of libolm.
account
account packages an account which stores the identity, one time keys and fallback keys.
account packages an account which stores the identity, one time keys and fallback keys.
cipher
Package cipher provides the methods and structs to do encryptions for olm/megolm.
Package cipher provides the methods and structs to do encryptions for olm/megolm.
crypto
Package crpyto provides the nessesary encryption methods for olm/megolm
Package crpyto provides the nessesary encryption methods for olm/megolm
megolm
megolm provides the ratchet used by the megolm protocol
megolm provides the ratchet used by the megolm protocol
olm
olm provides the ratchet used by the olm protocol
olm provides the ratchet used by the olm protocol
pk
session
Package session provides the different types of sessions for en/decrypting of messages
Package session provides the different types of sessions for en/decrypting of messages
Package verificationhelper provides a helper for the interactive verification process according to [Section 11.12.2] of the Spec.
Package verificationhelper provides a helper for the interactive verification process according to [Section 11.12.2] of the Spec.

Jump to

Keyboard shortcuts

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