common

package
v0.0.0-...-9835270 Latest Latest
Warning

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

Go to latest
Published: Sep 22, 2021 License: AGPL-3.0, Apache-2.0 Imports: 43 Imported by: 0

Documentation

Overview

Package auth implements authentication checks and storage.

Index

Constants

View Source
const DeleteMark = "__D__"
View Source
const HeaderLengthBytes = 4 // size of uint32
View Source
const MagicNum = 0xF0F0F0F0
View Source
const MagicNumBytes = 4 // size of uint32
View Source
const MaxSpanBytesLength = 1024

MaxSpanBytesLength is at least 136 for jaeger, if a span carrier length exceed this value, it will be discarded

View Source
const SpanKey = "span"

Variables

View Source
var DefaultKeyCount = func() map[string]int {
	m := make(map[string]int)
	m["curve25519"] = 50
	m["signed_curve25519"] = 50
	return m
}
View Source
var DoCompress = utils.DoCompress
View Source
var DoUnCompress = utils.DoUnCompress
View Source
var DomainFromID = utils.DomainFromID
View Source
var ErrRoomNoExists = errors.New("Room does not exist")

ErrRoomNoExists is returned when trying to lookup the state of a room that doesn't exist

View Source
var GetStringHash = utils.GetStringHash
View Source
var InitKeyCount = func() map[string]int {
	m := make(map[string]int)
	m["curve25519"] = 0
	m["signed_curve25519"] = 0
	return m
}
View Source
var LoadDomainFromDB = false
View Source
var PathExists = utils.PathExists

Functions

func BuildDevice

func BuildDevice(idg *uid.UidGenerator, did *string, isHuman, genNewDevice bool) (string, string, error)

func BuildEvent

func BuildEvent(
	builder *gomatrixserverlib.EventBuilder, domain string, cfg config.Dendrite,
	idg *uid.UidGenerator,
) (*gomatrixserverlib.Event, error)

BuildEvent builds a Matrix event using the event builder and roomserver query API client provided. If also fills roomserver query API response (if provided) in case the function calling FillBuilder needs to use it. Returns ErrRoomNoExists if the state of the room could not be retrieved because the room doesn't exist Returns an error if something else went wrong

func BuildPreBatch

func BuildPreBatch(streamPos, timestamp int64) string

func BuildRandomURLEncString

func BuildRandomURLEncString() (string, error)

func BuildStaticURLEncString

func BuildStaticURLEncString() (string, error)

func BuildSuperAdminToken

func BuildSuperAdminToken(key, id, loc, userId, deviceIdentifier string,
	guest bool, deviceID, deviceType string,
	human bool, ts int64,
) (string, error)

func BuildToken

func BuildToken(key, id, loc, userId, deviceIdentifier string,
	guest bool, deviceID, deviceType string,
	human bool,
) (string, error)

func BytesToUint32

func BytesToUint32(i []byte) uint32

func CalcStringHashCode

func CalcStringHashCode(str string) uint32

func CalcStringHashCode64

func CalcStringHashCode64(str string) uint64

func CheckValidDomain

func CheckValidDomain(id string, domains []string) bool

func ContextWithSpan

func ContextWithSpan(ctx context.Context, span opentracing.Span) context.Context

store a span into context.Context, so it can be passed to other place

func CreateDatabase

func CreateDatabase(driver, addr, name string) error

func EndTransaction

func EndTransaction(txn Transaction, succeeded *bool)

EndTransaction ends a transaction. If the transaction succeeded then it is committed, otherwise it is rolledback.

func ExportMetricsBeforeSending

func ExportMetricsBeforeSending(span opentracing.Span, metricName string, protocol string)

export metric sob, som before sending, argument protocal can choose from: kafka|nats|http

func ExtractAccessToken

func ExtractAccessToken(req *http.Request) (string, error)

func ExtractToken

func ExtractToken(key, id, loc, token string) (*authtypes.Device, bool, error)

func FilterEventTypes

func FilterEventTypes(events *[]gomatrixserverlib.ClientEvent, types *[]string, notTypes *[]string) *[]gomatrixserverlib.ClientEvent

func FromBase64

func FromBase64(in string) []byte

func GetDBInstance

func GetDBInstance(name string, cfg core.IConfig) (interface{}, error)

func GetDeviceMac

func GetDeviceMac(deviceID string) string

func GetDomainByUserID

func GetDomainByUserID(userID string) string

func GetGaugeInstance

func GetGaugeInstance() mon.LabeledGauge

func GetJsonResponse

func GetJsonResponse(data []byte) util.JSONResponse

func GetMsgType

func GetMsgType(content map[string]interface{}) (string, bool)

func GetProcessorMultiplexer

func GetProcessorMultiplexer() core.IMultiplexer

func GetRemoteIP

func GetRemoteIP(r *http.Request) string

func GetSyncInstance

func GetSyncInstance(key string, total uint32) uint32

func GetTransportMultiplexer

func GetTransportMultiplexer() core.IMultiplexer

func InjectSpanToHeader

func InjectSpanToHeader(span opentracing.Span) map[string]string

func InjectSpanToHeaderForSending

func InjectSpanToHeaderForSending(span opentracing.Span) map[string]string

func IsActualDevice

func IsActualDevice(deviceType string) bool

func IsCreatingDirectRoomEv

func IsCreatingDirectRoomEv(ev *gomatrixserverlib.Event) (bool, error)

func IsExtEvent

func IsExtEvent(ev *gomatrixserverlib.ClientEvent) bool

func IsMediaEv

func IsMediaEv(content map[string]interface{}) bool

func IsRelatedRequest

func IsRelatedRequest(key string, instance, total uint32, multiWrite bool) bool

func IsRelatedSyncRequest

func IsRelatedSyncRequest(reqInstance, curInstance, total uint32, multiWrite bool) bool

func IsStateClientEv

func IsStateClientEv(ev *gomatrixserverlib.ClientEvent) bool

func IsStateEv

func IsStateEv(ev *gomatrixserverlib.Event) bool

func IsUniqueConstraintViolationErr

func IsUniqueConstraintViolationErr(err error) bool

IsUniqueConstraintViolationErr returns true if the error is a postgresql unique_violation error

func LogStack

func LogStack()

func MakeAuthAPI

func MakeAuthAPI(
	metricsName string, cache service.Cache, cfg config.Dendrite, devFilter *filter.SimpleFilter,
	histogram mon.LabeledHistogram,
	f func(*http.Request, *authtypes.Device) util.JSONResponse,
) http.Handler

MakeAuthAPI turns a util.JSONRequestHandler function into an http.Handler which checks the access token in the request.

func MakeExternalAPI

func MakeExternalAPI(metricsName string, f func(*http.Request) util.JSONResponse) http.Handler

MakeExternalAPI turns a util.JSONRequestHandler function into an http.Handler. This is used for APIs that are called from the internet.

func MakeFedAPI

MakeFedAPI makes an http.Handler that checks matrix federation authentication.

func MakeInternalAPI

func MakeInternalAPI(metricsName string, f func(*http.Request) util.JSONResponse) http.Handler

MakeInternalAPI turns a util.JSONRequestHandler function into an http.Handler. This is used for APIs that are internal to dendrite. If we are passed a tracing context in the request headers then we use that as the parent of any tracing spans we create.

func MakeInternalAuthAPI

func MakeInternalAuthAPI(metricsName string, cache service.Cache, f func(*http.Request, *authtypes.Device) util.JSONResponse) http.Handler

func NatsWrapHandler

func NatsWrapHandler(handler nats.MsgHandler) nats.MsgHandler

func NatsWrapHandlerWithContext

func NatsWrapHandlerWithContext(metricName string, handler MsgHandlerWithContext) nats.MsgHandler

func PanicTrace

func PanicTrace(kb int) []byte

func ParseNatsData

func ParseNatsData(data []byte) ([]byte, opentracing.HTTPHeadersCarrier)

func Register

func Register(name string, f func(string, string, string, string, string, bool) (interface{}, error))

can't use skunkworks log

func SetProcessorMultiplexer

func SetProcessorMultiplexer(multp core.IMultiplexer)

func SetTransportMultiplexer

func SetTransportMultiplexer(multp core.IMultiplexer)

func SetupHTTPAPI

func SetupHTTPAPI(servMux *http.ServeMux, apiMux http.Handler)

SetupHTTPAPI registers an HTTP API mux under /api and sets up a metrics listener.

func SpanFromContext

func SpanFromContext(ctx context.Context) opentracing.Span

restore a span from context.Context, so it can be the parent of another child or follow span

func SplitMxc

func SplitMxc(s string) (domain, netdiskID string)

func StartSobSomSpan

func StartSobSomSpan(ctx context.Context, operationName string) (opentracing.Span, context.Context)

create a follow span from the span stored in context.Context

func StartSomSpan

func StartSomSpan(ctx context.Context, operationName string) (opentracing.Span, context.Context)

create a follow span from the span stored in context.Context

func StartSpanFromContext

func StartSpanFromContext(ctx context.Context, operationName string,
	opts ...opentracing.StartSpanOption) (opentracing.Span, context.Context)

create a follow span from the span stored in context.Context

func StartSpanFromMsgAfterReceived

func StartSpanFromMsgAfterReceived(metricName string, msg interface{}) opentracing.Span

func StripPrefix

func StripPrefix(prefix string, h http.Handler) http.HandlerFunc

func ToBase64

func ToBase64(b []byte) string

func TxStmt

func TxStmt(transaction *sql.Tx, statement *sql.Stmt) *sql.Stmt

TxStmt wraps an SQL stmt inside an optional transaction. If the transaction is nil then it returns the original statement that will run outside of a transaction. Otherwise returns a copy of the statement that will run inside the transaction.

func Uint32ToBytes

func Uint32ToBytes(i uint32) []byte

func UnmarshalJSON

func UnmarshalJSON(req *http.Request, iface interface{}) error

func VerifyToken

func VerifyToken(token string, requestURI string, cache service.Cache, cfg config.Dendrite, devFilter *filter.SimpleFilter) (*authtypes.Device, *util.JSONResponse)

func WithTransaction

func WithTransaction(db *sql.DB, fn func(txn *sql.Tx) error) (err error)

WithTransaction runs a block of code passing in an SQL transaction If the code returns an error or panics then the transactions is rolledback Otherwise the transaction is committed.

func WrapHandlerInCORS

func WrapHandlerInCORS(h http.Handler) http.HandlerFunc

WrapHandlerInCORS adds CORS headers to all responses, including all error responses. Handles OPTIONS requests directly.

Types

type AliasesContent

type AliasesContent struct {
	Aliases []string `json:"aliases"`
}

AliasesContent is the event content for http://matrix.org/docs/spec/client_server/r0.2.0.html#m-room-aliases

type AvatarContent

type AvatarContent struct {
	Info          ImageInfo `json:"info,omitempty"`
	URL           string    `json:"url"`
	ThumbnailURL  string    `json:"thumbnail_url,omitempty"`
	ThumbnailInfo ImageInfo `json:"thumbnail_info,omitempty"`
}

AvatarContent is the event content for http://matrix.org/docs/spec/client_server/r0.2.0.html#m-room-avatar

type CanonicalAliasContent

type CanonicalAliasContent struct {
	Alias string `json:"alias"`
}

CanonicalAliasContent is the event content for http://matrix.org/docs/spec/client_server/r0.2.0.html#m-room-canonical-alias

type ComplexCache

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

func NewComplexCache

func NewComplexCache(db model.AccountsDatabase, cache RawCache) *ComplexCache

func (*ComplexCache) GetAvatarURL

func (c *ComplexCache) GetAvatarURL(
	ctx context.Context,
	userID string,
) (string, error)

func (*ComplexCache) GetDisplayName

func (c *ComplexCache) GetDisplayName(
	ctx context.Context,
	userID string,
) (string, error)

func (*ComplexCache) GetProfileByUserID

func (c *ComplexCache) GetProfileByUserID(
	ctx context.Context,
	userID string,
) (string, string, error)

func (*ComplexCache) SetAvatarURL

func (c *ComplexCache) SetAvatarURL(
	ctx context.Context,
	userID string,
	avatarURL string,
) error

func (*ComplexCache) SetDefaultAvatarURL

func (c *ComplexCache) SetDefaultAvatarURL(avatarURL string)

func (*ComplexCache) SetDisplayName

func (c *ComplexCache) SetDisplayName(
	ctx context.Context,
	userID string,
	displayName string,
) error

func (*ComplexCache) SetProfile

func (c *ComplexCache) SetProfile(
	ctx context.Context,
	userID string,
	displayName string,
	avatarURL string,
) error

type ContextMsg

type ContextMsg struct {
	Ctx context.Context
	Msg interface{}
}

type CreateContent

type CreateContent struct {
	Creator  string `json:"creator"`
	Federate *bool  `json:"m.federate,omitempty"`
	IsDirect *bool  `json:"is_direct,omitempty"`

	//used by secrect group
	EnableWatermark    *bool `json:"enable_watermark,omitempty"`
	Version            *int  `json:"version,omitempty"`
	IsSecret           *bool `json:"is_secret,omitempty"`
	EnableFavorite     *bool `json:"enable_favorite,omitempty"`
	EnableSnapshot     *bool `json:"enable_snapshot,omitempty"`
	EnableForward      *bool `json:"enable_forward,omitempty"`
	IsChannel          *bool `json:"is_channel,omitempty"`
	IsOrganizationRoom *bool `json:"is_organization_room,omitempty"`
	IsGroupRoom        *bool `json:"is_group_room,omitempty"`
	RoomType           *int  `json:"room_type,omitempty"`
}

CreateContent is the event content for http://matrix.org/docs/spec/client_server/r0.2.0.html#m-room-create

type DescContent

type DescContent struct {
	Desc string `json:"desc"`
}

type FedDomainInfo

type FedDomainInfo struct {
	Name   string `json:"name"`
	Domain string `json:"domain"`
	Host   string `json:"host"`
	Port   int    `json:"port"`
}

type FedDomains

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

func NewFedDomains

func NewFedDomains(settings *Settings) *FedDomains

func (*FedDomains) GetAllDomainInfos

func (f *FedDomains) GetAllDomainInfos() []FedDomainInfo

func (*FedDomains) GetAllFedDomains

func (f *FedDomains) GetAllFedDomains() []string

func (*FedDomains) GetDomainHost

func (f *FedDomains) GetDomainHost(domain string) (string, bool)

func (*FedDomains) GetDomainInfo

func (f *FedDomains) GetDomainInfo(domain string) (FedDomainInfo, bool)

func (*FedDomains) LoadCache

func (f *FedDomains) LoadCache()

func (*FedDomains) OnFedDomainsUpdate

func (f *FedDomains) OnFedDomainsUpdate(domains []FedDomainInfo)

type GuestAccessContent

type GuestAccessContent struct {
	GuestAccess string `json:"guest_access"`
}

GuestAccessContent is the event content for https://matrix.org/docs/spec/client_server/r0.2.0.html#m-room-guest-access

type HistoryVisibilityContent

type HistoryVisibilityContent struct {
	HistoryVisibility string `json:"history_visibility"`
}

HistoryVisibilityContent is the event content for http://matrix.org/docs/spec/client_server/r0.2.0.html#m-room-history-visibility

type Hooks

type Hooks struct{}

Hooks satisfies the sqlhook.Hooks interface

func (*Hooks) After

func (h *Hooks) After(ctx context.Context, query string, args ...interface{}) (context.Context, error)

After hook will get the timestamp registered on the Before hook and print the elapsed time

func (*Hooks) Before

func (h *Hooks) Before(ctx context.Context, query string, args ...interface{}) (context.Context, error)

Before hook will print the query with it's args and return the context with the timestamp

func (*Hooks) Error

func (h *Hooks) Error(ctx context.Context, errstr error, query string, args ...interface{})

After hook will get the timestamp registered on the Before hook and print the elapsed time

type ImageInfo

type ImageInfo struct {
	Mimetype string `json:"mimetype"`
	Height   int64  `json:"h"`
	Width    int64  `json:"w"`
	Size     int64  `json:"size"`
}

ImageInfo implements the ImageInfo structure from http://matrix.org/docs/spec/client_server/r0.2.0.html#m-room-avatar

type JoinRulesContent

type JoinRulesContent struct {
	JoinRule string `json:"join_rule"`
}

JoinRulesContent is the event content for http://matrix.org/docs/spec/client_server/r0.2.0.html#m-room-join-rules

type MsgHandlerWithContext

type MsgHandlerWithContext func(ctx context.Context, msg *nats.Msg)

type MultiplexerMng

type MultiplexerMng struct {
	// contains filtered or unexported fields
}
var MultiplexerMngInsance *MultiplexerMng

type NameContent

type NameContent struct {
	Name string `json:"name"`
}

NameContent is the event content for https://matrix.org/docs/spec/client_server/r0.2.0.html#m-room-name

type PowerLevelContent

type PowerLevelContent struct {
	EventsDefault int            `json:"events_default"`
	Invite        int            `json:"invite"`
	StateDefault  int            `json:"state_default"`
	Redact        int            `json:"redact"`
	Ban           int            `json:"ban"`
	UsersDefault  int            `json:"users_default"`
	Events        map[string]int `json:"events"`
	Kick          int            `json:"kick"`
	Users         map[string]int `json:"users"`
}

PowerLevelContent is the event content for http://matrix.org/docs/spec/client_server/r0.2.0.html#m-room-power-levels

func InitialPowerLevelsContent

func InitialPowerLevelsContent(roomCreator string) PowerLevelContent

InitialPowerLevelsContent returns the initial values for m.room.power_levels on room creation if they have not been specified. http://matrix.org/docs/spec/client_server/r0.2.0.html#m-room-power-levels https://github.com/matrix-org/synapse/blob/v0.19.2/synapse/handlers/room.py#L294

type PublicKey

type PublicKey struct {
	KeyValidityURL string `json:"key_validity_url"`
	PublicKey      string `json:"public_key"`
}

PublicKey is the PublicKeys structure in https://matrix.org/docs/spec/client_server/r0.2.0.html#m-room-third-party-invite

type RawCache

type RawCache interface {
	GetProfileByUserID(userID string) *authtypes.Profile
	GetProfileLessByUserID(userID string) (string, string, bool)
	GetAvatarURLByUser(userID string) (string, bool)
	GetDisplayNameByUser(userID string) (string, bool)

	SetProfile(userID, displayName, avatar string) error
	ExpireProfile(userID string) error

	DelProfile(userID string) error
	DelAvatar(userID string) error
	DelDisplayName(userID string) error
}

type Result

type Result struct {
	Index   int64  `json:"index"`
	Success bool   `json:"success"`
	ErrMsg  string `json:"errmsg,omitempty"`
}

type RpcCB

type RpcCB interface {
	GetTopic() string
	//GetCB() nats.MsgHandler
	GetCB() MsgHandlerWithContext
	Clean()
}

type RpcClient

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

func NewRpcClient

func NewRpcClient(url string, idg *uid.UidGenerator) *RpcClient

func (*RpcClient) Pub

func (nc *RpcClient) Pub(topic string, bytes []byte)

TODO: is it necessary to add context/span/monitor like RequestWithContext for Pub()?

func (*RpcClient) PubObj

func (nc *RpcClient) PubObj(topic string, obj interface{})

TODO: is it necessary to add context/span/monitor like RequestWithContext for PubObj()?

func (*RpcClient) Reply

func (nc *RpcClient) Reply(topic string, handler nats.MsgHandler)

func (*RpcClient) ReplyGrp

func (nc *RpcClient) ReplyGrp(topic, grp string, handler nats.MsgHandler)

func (*RpcClient) ReplyGrpWithContext

func (nc *RpcClient) ReplyGrpWithContext(topic, grp string, handler MsgHandlerWithContext)

func (*RpcClient) ReplyWithContext

func (nc *RpcClient) ReplyWithContext(topic string, handler MsgHandlerWithContext)

func (*RpcClient) Request

func (nc *RpcClient) Request(topic string, bytes []byte, timeout int) ([]byte, error)

Request is used for rpc client, Reply/ReplyGrp is used for rpc server, SubRaw is used for rpc client but now is deprecated

func (*RpcClient) RequestWithContext

func (nc *RpcClient) RequestWithContext(ctx context.Context,
	topic string, bytes []byte, timeout int) ([]byte, error)

must be careful to use RequestWithContext, because some nats rpc server dose not support parseNatsData!!!

func (*RpcClient) Start

func (nc *RpcClient) Start(clean bool)

func (*RpcClient) SubRaw

func (nc *RpcClient) SubRaw(cb RpcCB)

func (*RpcClient) Unsubscribe

func (nc *RpcClient) Unsubscribe(cb RpcCB)

type SettingCache

type SettingCache interface {
	GetSetting(settingKey string) (int64, error)
	GetSettingRaw(settingKey string) (string, error)
	SetSetting(settingKey string, val string) error
}

type Settings

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

func NewSettings

func NewSettings(cache SettingCache) *Settings

func (*Settings) GetAutoLogoutTime

func (c *Settings) GetAutoLogoutTime() int64

func (*Settings) GetFederationDomains

func (c *Settings) GetFederationDomains() (ret []FedDomainInfo)

func (*Settings) GetMessageVisilibityTime

func (c *Settings) GetMessageVisilibityTime() int64

func (*Settings) RegisterFederationDomainsUpdateCallback

func (c *Settings) RegisterFederationDomainsUpdateCallback(cb func([]FedDomainInfo))

func (*Settings) UpdateSetting

func (c *Settings) UpdateSetting(key, val string)

type SettingsConsumer

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

func NewSettingConsumer

func NewSettingConsumer(underlying, name string, settings *Settings) *SettingsConsumer

func (*SettingsConsumer) OnMessage

func (c *SettingsConsumer) OnMessage(ctx context.Context, topic string, partition int32, data []byte, rawMsg interface{})

func (*SettingsConsumer) Start

func (c *SettingsConsumer) Start() error

type ThirdPartyInviteContent

type ThirdPartyInviteContent struct {
	DisplayName    string      `json:"display_name"`
	KeyValidityURL string      `json:"key_validity_url"`
	PublicKey      string      `json:"public_key"`
	PublicKeys     []PublicKey `json:"public_keys"`
}

ThirdPartyInviteContent is the content event for https://matrix.org/docs/spec/client_server/r0.2.0.html#m-room-third-party-invite

type TopicContent

type TopicContent struct {
	Topic string `json:"topic"`
}

TopicContent is the event content for https://matrix.org/docs/spec/client_server/r0.2.0.html#m-room-topic

type Transaction

type Transaction interface {
	// Commit the transaction
	Commit() error
	// Rollback the transaction.
	Rollback() error
}

A Transaction is something that can be committed or rolledback.

type VisibilityContent

type VisibilityContent struct {
	Visibility string `json:"visibility"`
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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