server

package
v0.31.1 Latest Latest
Warning

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

Go to latest
Published: Nov 11, 2024 License: BSD-3-Clause Imports: 73 Imported by: 17

Documentation

Index

Constants

View Source
const (
	PublicCategory                  = "public"
	PrivateCategory                 = "private"
	UnknownCategory                 = "unknown"
	CacheExpirationMax              = 7 * 24 * 3600 * time.Second // 7 days
	CacheExpirationMin              = 3 * 24 * 3600 * time.Second // 3 days
	DefaultPeerLoginExpiration      = 24 * time.Hour
	DefaultPeerInactivityExpiration = 10 * time.Minute
)
View Source
const (
	UDP   Protocol = "udp"
	DTLS  Protocol = "dtls"
	TCP   Protocol = "tcp"
	HTTP  Protocol = "http"
	HTTPS Protocol = "https"
	NONE  Provider = "none"
)
View Source
const (
	// SubnetSize is a size of the subnet of the global network, e.g.  100.77.0.0/16
	SubnetSize = 16
	// NetSize is a global network size 100.64.0.0/10
	NetSize = 10

	// AllowedIPsFormat generates Wireguard AllowedIPs format (e.g. 100.64.30.1/32)
	AllowedIPsFormat = "%s/32"
)
View Source
const (
	// PATPrefix is the globally used, 4 char prefix for personal access tokens
	PATPrefix = "nbp_"
	// PATSecretLength number of characters used for the secret inside the token
	PATSecretLength = 30
	// PATChecksumLength number of characters used for the encoded checksum of the secret inside the token
	PATChecksumLength = 6
	// PATLength total number of characters used for the token
	PATLength = 40
)
View Source
const (
	// PolicyTrafficActionAccept indicates that the traffic is accepted
	PolicyTrafficActionAccept = PolicyTrafficActionType("accept")
	// PolicyTrafficActionDrop indicates that the traffic is dropped
	PolicyTrafficActionDrop = PolicyTrafficActionType("drop")
)
View Source
const (
	// PolicyRuleProtocolALL type of traffic
	PolicyRuleProtocolALL = PolicyRuleProtocolType("all")
	// PolicyRuleProtocolTCP type of traffic
	PolicyRuleProtocolTCP = PolicyRuleProtocolType("tcp")
	// PolicyRuleProtocolUDP type of traffic
	PolicyRuleProtocolUDP = PolicyRuleProtocolType("udp")
	// PolicyRuleProtocolICMP type of traffic
	PolicyRuleProtocolICMP = PolicyRuleProtocolType("icmp")
)
View Source
const (
	// PolicyRuleFlowDirect allows traffic from source to destination
	PolicyRuleFlowDirect = PolicyRuleDirection("direct")
	// PolicyRuleFlowBidirect allows traffic to both directions
	PolicyRuleFlowBidirect = PolicyRuleDirection("bidirect")
)
View Source
const (
	// DefaultRuleName is a name for the Default rule that is created for every account
	DefaultRuleName = "Default"
	// DefaultRuleDescription is a description for the Default rule that is created for every account
	DefaultRuleDescription = "This is a default rule that allows connections between all the resources"
	// DefaultPolicyName is a name for the Default policy that is created for every account
	DefaultPolicyName = "Default"
	// DefaultPolicyDescription is a description for the Default policy that is created for every account
	DefaultPolicyDescription = "This is a default policy that allows connections between all the resources"
)
View Source
const (
	// SetupKeyReusable is a multi-use key (can be used for multiple machines)
	SetupKeyReusable SetupKeyType = "reusable"
	// SetupKeyOneOff is a single use key (can be used only once)
	SetupKeyOneOff SetupKeyType = "one-off"

	// DefaultSetupKeyDuration = 1 month
	DefaultSetupKeyDuration = 24 * 30 * time.Hour
	// DefaultSetupKeyName is a default name of the default setup key
	DefaultSetupKeyName = "Default key"
	// SetupKeyUnlimitedUsage indicates an unlimited usage of a setup key
	SetupKeyUnlimitedUsage = 0
)
View Source
const (
	UserRoleOwner        UserRole = "owner"
	UserRoleAdmin        UserRole = "admin"
	UserRoleUser         UserRole = "user"
	UserRoleUnknown      UserRole = "unknown"
	UserRoleBillingAdmin UserRole = "billing_admin"

	UserStatusActive   UserStatus = "active"
	UserStatusDisabled UserStatus = "disabled"
	UserStatusInvited  UserStatus = "invited"

	UserIssuedAPI         = "api"
	UserIssuedIntegration = "integration"
)
View Source
const (
	// DefaultDeviceAuthFlowScope defines the bare minimum scope to request in the device authorization flow
	DefaultDeviceAuthFlowScope string = "openid"
)

Variables

This section is empty.

Functions

func AllocatePeerIP

func AllocatePeerIP(ipNet net.IPNet, takenIps []net.IP) (net.IP, error)

AllocatePeerIP pics an available IP from an net.IPNet. This method considers already taken IPs and reuses IPs if there are gaps in takenIps E.g. if ipNet=100.30.0.0/16 and takenIps=[100.30.0.1, 100.30.0.4] then the result would be 100.30.0.2 or 100.30.0.3

func ConvertSliceToMap added in v0.29.3

func ConvertSliceToMap(existingLabels []string) map[string]struct{}

func Hash

func Hash(s string) uint32

func MigrateFileStoreToSqlite added in v0.28.0

func MigrateFileStoreToSqlite(ctx context.Context, dataDir string) error

MigrateFileStoreToSqlite migrates the file store to the SQLite store.

func ToResponseProto

func ToResponseProto(configProto Protocol) proto.HostConfig_Protocol

Types

type Account

type Account struct {
	// we have to name column to aid as it collides with Network.Id when work with associations
	Id string `gorm:"primaryKey"`

	// User.Id it was created by
	CreatedBy              string
	CreatedAt              time.Time
	Domain                 string `gorm:"index"`
	DomainCategory         string
	IsDomainPrimaryAccount bool
	SetupKeys              map[string]*SetupKey              `gorm:"-"`
	SetupKeysG             []SetupKey                        `json:"-" gorm:"foreignKey:AccountID;references:id"`
	Network                *Network                          `gorm:"embedded;embeddedPrefix:network_"`
	Peers                  map[string]*nbpeer.Peer           `gorm:"-"`
	PeersG                 []nbpeer.Peer                     `json:"-" gorm:"foreignKey:AccountID;references:id"`
	Users                  map[string]*User                  `gorm:"-"`
	UsersG                 []User                            `json:"-" gorm:"foreignKey:AccountID;references:id"`
	Groups                 map[string]*nbgroup.Group         `gorm:"-"`
	GroupsG                []nbgroup.Group                   `json:"-" gorm:"foreignKey:AccountID;references:id"`
	Policies               []*Policy                         `gorm:"foreignKey:AccountID;references:id"`
	Routes                 map[route.ID]*route.Route         `gorm:"-"`
	RoutesG                []route.Route                     `json:"-" gorm:"foreignKey:AccountID;references:id"`
	NameServerGroups       map[string]*nbdns.NameServerGroup `gorm:"-"`
	NameServerGroupsG      []nbdns.NameServerGroup           `json:"-" gorm:"foreignKey:AccountID;references:id"`
	DNSSettings            DNSSettings                       `gorm:"embedded;embeddedPrefix:dns_settings_"`
	PostureChecks          []*posture.Checks                 `gorm:"foreignKey:AccountID;references:id"`
	// Settings is a dictionary of Account settings
	Settings *Settings `gorm:"embedded;embeddedPrefix:settings_"`
}

Account represents a unique account of the system

func (*Account) Copy

func (a *Account) Copy() *Account

func (*Account) DeletePeer added in v0.10.6

func (a *Account) DeletePeer(peerID string)

DeletePeer deletes peer from the account cleaning up all the references

func (*Account) FindGroupByName added in v0.26.4

func (a *Account) FindGroupByName(groupName string) (*nbgroup.Group, error)

FindGroupByName looks for a given group in the Account by name or returns error if the group wasn't found.

func (*Account) FindPeerByPubKey added in v0.10.6

func (a *Account) FindPeerByPubKey(peerPubKey string) (*nbpeer.Peer, error)

FindPeerByPubKey looks for a Peer by provided WireGuard public key in the Account or returns error if it wasn't found. It will return an object copy of the peer.

func (*Account) FindSetupKey added in v0.10.8

func (a *Account) FindSetupKey(setupKey string) (*SetupKey, error)

FindSetupKey looks for a given SetupKey in the Account or returns error if it wasn't found.

func (*Account) FindUser added in v0.10.5

func (a *Account) FindUser(userID string) (*User, error)

FindUser looks for a given user in the Account or returns error if user wasn't found.

func (*Account) FindUserPeers added in v0.13.0

func (a *Account) FindUserPeers(userID string) ([]*nbpeer.Peer, error)

FindUserPeers returns a list of peers that user owns (created)

func (*Account) GetExpiredPeers added in v0.14.2

func (a *Account) GetExpiredPeers() []*nbpeer.Peer

GetExpiredPeers returns peers that have been expired

func (*Account) GetGroup added in v0.12.0

func (a *Account) GetGroup(groupID string) *nbgroup.Group

GetGroup returns a group by ID if exists, nil otherwise

func (*Account) GetGroupAll

func (a *Account) GetGroupAll() (*nbgroup.Group, error)

func (*Account) GetInactivePeers added in v0.30.2

func (a *Account) GetInactivePeers() []*nbpeer.Peer

GetInactivePeers returns peers that have been expired by inactivity

func (*Account) GetNextInactivePeerExpiration added in v0.30.2

func (a *Account) GetNextInactivePeerExpiration() (time.Duration, bool)

GetNextInactivePeerExpiration returns the minimum duration in which the next peer of the account will expire if it was found. If there is no peer that expires this function returns false and a duration of 0. This function only considers peers that haven't been expired yet and that are not connected.

func (*Account) GetNextPeerExpiration added in v0.14.2

func (a *Account) GetNextPeerExpiration() (time.Duration, bool)

GetNextPeerExpiration returns the minimum duration in which the next peer of the account will expire if it was found. If there is no peer that expires this function returns false and a duration of 0. This function only considers peers that haven't been expired yet and that are connected.

func (*Account) GetPeer added in v0.13.0

func (a *Account) GetPeer(peerID string) *nbpeer.Peer

GetPeer looks up a Peer by ID

func (*Account) GetPeerGroupsList added in v0.26.5

func (a *Account) GetPeerGroupsList(peerID string) []string

GetPeerGroupsList return with the list of groups ID.

func (*Account) GetPeerNetworkMap added in v0.14.3

func (a *Account) GetPeerNetworkMap(
	ctx context.Context,
	peerID string,
	peersCustomZone nbdns.CustomZone,
	validatedPeersMap map[string]struct{},
	metrics *telemetry.AccountManagerMetrics,
) *NetworkMap

GetPeerNetworkMap returns the networkmap for the given peer ID.

func (*Account) GetPeers added in v0.10.6

func (a *Account) GetPeers() []*nbpeer.Peer

GetPeers returns a list of all Account peers

func (*Account) GetPeersCustomZone added in v0.28.8

func (a *Account) GetPeersCustomZone(ctx context.Context, dnsDomain string) nbdns.CustomZone

func (*Account) GetPeersWithExpiration added in v0.14.2

func (a *Account) GetPeersWithExpiration() []*nbpeer.Peer

GetPeersWithExpiration returns a list of peers that have Peer.LoginExpirationEnabled set to true and that were added by a user

func (*Account) GetPeersWithInactivity added in v0.30.2

func (a *Account) GetPeersWithInactivity() []*nbpeer.Peer

GetPeersWithInactivity eturns a list of peers that have Peer.InactivityExpirationEnabled set to true and that were added by a user

func (*Account) GetRoutesByPrefixOrDomains added in v0.28.0

func (a *Account) GetRoutesByPrefixOrDomains(prefix netip.Prefix, domains domain.List) []*route.Route

GetRoutesByPrefixOrDomains return list of routes by account and route prefix

func (*Account) UpdatePeer added in v0.10.6

func (a *Account) UpdatePeer(update *nbpeer.Peer)

UpdatePeer saves new or replaces existing peer

func (*Account) UpdateSettings added in v0.14.0

func (a *Account) UpdateSettings(update *Settings) *Account

UpdateSettings saves new account settings

func (*Account) UserGroupsAddToPeers added in v0.22.3

func (a *Account) UserGroupsAddToPeers(userID string, groups ...string)

UserGroupsAddToPeers adds groups to all peers of user

func (*Account) UserGroupsRemoveFromPeers added in v0.22.3

func (a *Account) UserGroupsRemoveFromPeers(userID string, groups ...string)

UserGroupsRemoveFromPeers removes groups from all peers of user

type AccountDNSSettings added in v0.30.0

type AccountDNSSettings struct {
	DNSSettings DNSSettings `gorm:"embedded;embeddedPrefix:dns_settings_"`
}

AccountDNSSettings used in gorm to only load dns settings and not whole account

type AccountManager

type AccountManager interface {
	GetOrCreateAccountByUser(ctx context.Context, userId, domain string) (*Account, error)
	GetAccount(ctx context.Context, accountID string) (*Account, error)
	CreateSetupKey(ctx context.Context, accountID string, keyName string, keyType SetupKeyType, expiresIn time.Duration,
		autoGroups []string, usageLimit int, userID string, ephemeral bool) (*SetupKey, error)
	SaveSetupKey(ctx context.Context, accountID string, key *SetupKey, userID string) (*SetupKey, error)
	CreateUser(ctx context.Context, accountID, initiatorUserID string, key *UserInfo) (*UserInfo, error)
	DeleteUser(ctx context.Context, accountID, initiatorUserID string, targetUserID string) error
	DeleteRegularUsers(ctx context.Context, accountID, initiatorUserID string, targetUserIDs []string) error
	InviteUser(ctx context.Context, accountID string, initiatorUserID string, targetUserID string) error
	ListSetupKeys(ctx context.Context, accountID, userID string) ([]*SetupKey, error)
	SaveUser(ctx context.Context, accountID, initiatorUserID string, update *User) (*UserInfo, error)
	SaveOrAddUser(ctx context.Context, accountID, initiatorUserID string, update *User, addIfNotExists bool) (*UserInfo, error)
	SaveOrAddUsers(ctx context.Context, accountID, initiatorUserID string, updates []*User, addIfNotExists bool) ([]*UserInfo, error)
	GetSetupKey(ctx context.Context, accountID, userID, keyID string) (*SetupKey, error)
	GetAccountByID(ctx context.Context, accountID string, userID string) (*Account, error)
	AccountExists(ctx context.Context, accountID string) (bool, error)
	GetAccountIDByUserID(ctx context.Context, userID, domain string) (string, error)
	GetAccountIDFromToken(ctx context.Context, claims jwtclaims.AuthorizationClaims) (string, string, error)
	CheckUserAccessByJWTGroups(ctx context.Context, claims jwtclaims.AuthorizationClaims) error
	GetAccountFromPAT(ctx context.Context, pat string) (*Account, *User, *PersonalAccessToken, error)
	DeleteAccount(ctx context.Context, accountID, userID string) error
	MarkPATUsed(ctx context.Context, tokenID string) error
	GetUserByID(ctx context.Context, id string) (*User, error)
	GetUser(ctx context.Context, claims jwtclaims.AuthorizationClaims) (*User, error)
	ListUsers(ctx context.Context, accountID string) ([]*User, error)
	GetPeers(ctx context.Context, accountID, userID string) ([]*nbpeer.Peer, error)
	MarkPeerConnected(ctx context.Context, peerKey string, connected bool, realIP net.IP, account *Account) error
	DeletePeer(ctx context.Context, accountID, peerID, userID string) error
	UpdatePeer(ctx context.Context, accountID, userID string, peer *nbpeer.Peer) (*nbpeer.Peer, error)
	GetNetworkMap(ctx context.Context, peerID string) (*NetworkMap, error)
	GetPeerNetwork(ctx context.Context, peerID string) (*Network, error)
	AddPeer(ctx context.Context, setupKey, userID string, peer *nbpeer.Peer) (*nbpeer.Peer, *NetworkMap, []*posture.Checks, error)
	CreatePAT(ctx context.Context, accountID string, initiatorUserID string, targetUserID string, tokenName string, expiresIn int) (*PersonalAccessTokenGenerated, error)
	DeletePAT(ctx context.Context, accountID string, initiatorUserID string, targetUserID string, tokenID string) error
	GetPAT(ctx context.Context, accountID string, initiatorUserID string, targetUserID string, tokenID string) (*PersonalAccessToken, error)
	GetAllPATs(ctx context.Context, accountID string, initiatorUserID string, targetUserID string) ([]*PersonalAccessToken, error)
	GetUsersFromAccount(ctx context.Context, accountID, userID string) ([]*UserInfo, error)
	GetGroup(ctx context.Context, accountId, groupID, userID string) (*nbgroup.Group, error)
	GetAllGroups(ctx context.Context, accountID, userID string) ([]*nbgroup.Group, error)
	GetGroupByName(ctx context.Context, groupName, accountID string) (*nbgroup.Group, error)
	SaveGroup(ctx context.Context, accountID, userID string, group *nbgroup.Group) error
	SaveGroups(ctx context.Context, accountID, userID string, newGroups []*nbgroup.Group) error
	DeleteGroup(ctx context.Context, accountId, userId, groupID string) error
	DeleteGroups(ctx context.Context, accountId, userId string, groupIDs []string) error
	ListGroups(ctx context.Context, accountId string) ([]*nbgroup.Group, error)
	GroupAddPeer(ctx context.Context, accountId, groupID, peerID string) error
	GroupDeletePeer(ctx context.Context, accountId, groupID, peerID string) error
	GetPolicy(ctx context.Context, accountID, policyID, userID string) (*Policy, error)
	SavePolicy(ctx context.Context, accountID, userID string, policy *Policy, isUpdate bool) error
	DeletePolicy(ctx context.Context, accountID, policyID, userID string) error
	ListPolicies(ctx context.Context, accountID, userID string) ([]*Policy, error)
	GetRoute(ctx context.Context, accountID string, routeID route.ID, userID string) (*route.Route, error)
	CreateRoute(ctx context.Context, accountID string, prefix netip.Prefix, networkType route.NetworkType, domains domain.List, peerID string, peerGroupIDs []string, description string, netID route.NetID, masquerade bool, metric int, groups, accessControlGroupIDs []string, enabled bool, userID string, keepRoute bool) (*route.Route, error)
	SaveRoute(ctx context.Context, accountID, userID string, route *route.Route) error
	DeleteRoute(ctx context.Context, accountID string, routeID route.ID, userID string) error
	ListRoutes(ctx context.Context, accountID, userID string) ([]*route.Route, error)
	GetNameServerGroup(ctx context.Context, accountID, userID, nsGroupID string) (*nbdns.NameServerGroup, error)
	CreateNameServerGroup(ctx context.Context, accountID string, name, description string, nameServerList []nbdns.NameServer, groups []string, primary bool, domains []string, enabled bool, userID string, searchDomainsEnabled bool) (*nbdns.NameServerGroup, error)
	SaveNameServerGroup(ctx context.Context, accountID, userID string, nsGroupToSave *nbdns.NameServerGroup) error
	DeleteNameServerGroup(ctx context.Context, accountID, nsGroupID, userID string) error
	ListNameServerGroups(ctx context.Context, accountID string, userID string) ([]*nbdns.NameServerGroup, error)
	GetDNSDomain() string
	StoreEvent(ctx context.Context, initiatorID, targetID, accountID string, activityID activity.ActivityDescriber, meta map[string]any)
	GetEvents(ctx context.Context, accountID, userID string) ([]*activity.Event, error)
	GetDNSSettings(ctx context.Context, accountID string, userID string) (*DNSSettings, error)
	SaveDNSSettings(ctx context.Context, accountID string, userID string, dnsSettingsToSave *DNSSettings) error
	GetPeer(ctx context.Context, accountID, peerID, userID string) (*nbpeer.Peer, error)
	UpdateAccountSettings(ctx context.Context, accountID, userID string, newSettings *Settings) (*Account, error)
	LoginPeer(ctx context.Context, login PeerLogin) (*nbpeer.Peer, *NetworkMap, []*posture.Checks, error)                // used by peer gRPC API
	SyncPeer(ctx context.Context, sync PeerSync, account *Account) (*nbpeer.Peer, *NetworkMap, []*posture.Checks, error) // used by peer gRPC API
	GetAllConnectedPeers() (map[string]struct{}, error)
	HasConnectedChannel(peerID string) bool
	GetExternalCacheManager() ExternalCacheManager
	GetPostureChecks(ctx context.Context, accountID, postureChecksID, userID string) (*posture.Checks, error)
	SavePostureChecks(ctx context.Context, accountID, userID string, postureChecks *posture.Checks) error
	DeletePostureChecks(ctx context.Context, accountID, postureChecksID, userID string) error
	ListPostureChecks(ctx context.Context, accountID, userID string) ([]*posture.Checks, error)
	GetIdpManager() idp.Manager
	UpdateIntegratedValidatorGroups(ctx context.Context, accountID string, userID string, groups []string) error
	GroupValidation(ctx context.Context, accountId string, groups []string) (bool, error)
	GetValidatedPeers(account *Account) (map[string]struct{}, error)
	SyncAndMarkPeer(ctx context.Context, accountID string, peerPubKey string, meta nbpeer.PeerSystemMeta, realIP net.IP) (*nbpeer.Peer, *NetworkMap, []*posture.Checks, error)
	OnPeerDisconnected(ctx context.Context, accountID string, peerPubKey string) error
	SyncPeerMeta(ctx context.Context, peerPubKey string, meta nbpeer.PeerSystemMeta) error
	FindExistingPostureCheck(accountID string, checks *posture.ChecksDefinition) (*posture.Checks, error)
	GetAccountIDForPeerKey(ctx context.Context, peerKey string) (string, error)
	GetAccountSettings(ctx context.Context, accountID string, userID string) (*Settings, error)
	DeleteSetupKey(ctx context.Context, accountID, userID, keyID string) error
}

type AccountNetwork added in v0.29.3

type AccountNetwork struct {
	Network *Network `gorm:"embedded;embeddedPrefix:network_"`
}

Subclass used in gorm to only load network and not whole account

type AccountRequest added in v0.28.8

type AccountRequest struct {
	AccountID  string
	ResultChan chan *AccountResult
}

AccountRequest holds the result channel to return the requested account.

type AccountRequestBuffer added in v0.28.9

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

func NewAccountRequestBuffer added in v0.28.9

func NewAccountRequestBuffer(ctx context.Context, store Store) *AccountRequestBuffer

func (*AccountRequestBuffer) GetAccountWithBackpressure added in v0.28.9

func (ac *AccountRequestBuffer) GetAccountWithBackpressure(ctx context.Context, accountID string) (*Account, error)

type AccountResult added in v0.28.8

type AccountResult struct {
	Account *Account
	Err     error
}

AccountResult holds the account data or an error.

type AccountSettings added in v0.28.0

type AccountSettings struct {
	Settings *Settings `gorm:"embedded;embeddedPrefix:settings_"`
}

Subclass used in gorm to only load settings and not whole account

type Config

type Config struct {
	Stuns      []*Host
	TURNConfig *TURNConfig
	Relay      *Relay
	Signal     *Host

	Datadir                string
	DataStoreEncryptionKey string

	HttpConfig *HttpServerConfig

	IdpManagerConfig *idp.Config

	DeviceAuthorizationFlow *DeviceAuthorizationFlow

	PKCEAuthorizationFlow *PKCEAuthorizationFlow

	StoreConfig StoreConfig

	ReverseProxy ReverseProxy
}

Config of the Management service

func (Config) GetAuthAudiences added in v0.15.0

func (c Config) GetAuthAudiences() []string

GetAuthAudiences returns the audience from the http config and device authorization flow config

type DNSConfigCache added in v0.28.8

type DNSConfigCache struct {
	CustomZones      sync.Map
	NameServerGroups sync.Map
}

DNSConfigCache is a thread-safe cache for DNS configuration components

func (*DNSConfigCache) GetCustomZone added in v0.28.8

func (c *DNSConfigCache) GetCustomZone(key string) (*proto.CustomZone, bool)

GetCustomZone retrieves a cached custom zone

func (*DNSConfigCache) GetNameServerGroup added in v0.28.8

func (c *DNSConfigCache) GetNameServerGroup(key string) (*proto.NameServerGroup, bool)

GetNameServerGroup retrieves a cached name server group

func (*DNSConfigCache) SetCustomZone added in v0.28.8

func (c *DNSConfigCache) SetCustomZone(key string, value *proto.CustomZone)

SetCustomZone stores a custom zone in the cache

func (*DNSConfigCache) SetNameServerGroup added in v0.28.8

func (c *DNSConfigCache) SetNameServerGroup(key string, value *proto.NameServerGroup)

SetNameServerGroup stores a name server group in the cache

type DNSSettings added in v0.12.0

type DNSSettings struct {
	// DisabledManagementGroups groups whose DNS management is disabled
	DisabledManagementGroups []string `gorm:"serializer:json"`
}

DNSSettings defines dns settings at the account level

func (DNSSettings) Copy added in v0.12.0

func (d DNSSettings) Copy() DNSSettings

Copy returns a copy of the DNS settings

type DefaultAccountManager

type DefaultAccountManager struct {
	Store Store
	// contains filtered or unexported fields
}

func BuildManager

func BuildManager(
	ctx context.Context,
	store Store,
	peersUpdateManager *PeersUpdateManager,
	idpManager idp.Manager,
	singleAccountModeDomain string,
	dnsDomain string,
	eventStore activity.Store,
	geo *geolocation.Geolocation,
	userDeleteFromIDPEnabled bool,
	integratedPeerValidator integrated_validator.IntegratedValidator,
	metrics telemetry.AppMetrics,
) (*DefaultAccountManager, error)

BuildManager creates a new DefaultAccountManager with a provided Store

func (*DefaultAccountManager) AccountExists

func (am *DefaultAccountManager) AccountExists(ctx context.Context, accountID string) (bool, error)

AccountExists checks if an account exists.

func (*DefaultAccountManager) AddPeer

func (am *DefaultAccountManager) AddPeer(ctx context.Context, setupKey, userID string, peer *nbpeer.Peer) (*nbpeer.Peer, *NetworkMap, []*posture.Checks, error)

AddPeer adds a new peer to the Store. Each Account has a list of pre-authorized SetupKey and if no Account has a given key err with a code status.PermissionDenied will be returned, meaning the setup key is invalid or not found. If a User ID is provided, it means that we passed the authentication using JWT, then we look for account by User ID and register the peer to it. We also add the User ID to the peer metadata to identify registrant. If no userID provided, then fail with status.PermissionDenied Each new Peer will be assigned a new next net.IP from the Account.Network and Account.Network.LastIP will be updated (IP's are not reused). The peer property is just a placeholder for the Peer properties to pass further

func (*DefaultAccountManager) CheckGroupPermissions added in v0.30.0

func (am *DefaultAccountManager) CheckGroupPermissions(ctx context.Context, accountID, userID string) error

CheckGroupPermissions validates if a user has the necessary permissions to view groups

func (*DefaultAccountManager) CheckUserAccessByJWTGroups added in v0.25.0

func (am *DefaultAccountManager) CheckUserAccessByJWTGroups(ctx context.Context, claims jwtclaims.AuthorizationClaims) error

CheckUserAccessByJWTGroups checks if the user has access, particularly in cases where the admin enabled JWT group propagation and set the list of groups with access permissions.

func (*DefaultAccountManager) CreateNameServerGroup added in v0.9.8

func (am *DefaultAccountManager) CreateNameServerGroup(ctx context.Context, accountID string, name, description string, nameServerList []nbdns.NameServer, groups []string, primary bool, domains []string, enabled bool, userID string, searchDomainEnabled bool) (*nbdns.NameServerGroup, error)

CreateNameServerGroup creates and saves a new nameserver group

func (*DefaultAccountManager) CreatePAT added in v0.14.6

func (am *DefaultAccountManager) CreatePAT(ctx context.Context, accountID string, initiatorUserID string, targetUserID string, tokenName string, expiresIn int) (*PersonalAccessTokenGenerated, error)

CreatePAT creates a new PAT for the given user

func (*DefaultAccountManager) CreateRoute added in v0.8.9

func (am *DefaultAccountManager) CreateRoute(ctx context.Context, accountID string, prefix netip.Prefix, networkType route.NetworkType, domains domain.List, peerID string, peerGroupIDs []string, description string, netID route.NetID, masquerade bool, metric int, groups, accessControlGroupIDs []string, enabled bool, userID string, keepRoute bool) (*route.Route, error)

CreateRoute creates and saves a new route

func (*DefaultAccountManager) CreateSetupKey added in v0.9.2

func (am *DefaultAccountManager) CreateSetupKey(ctx context.Context, accountID string, keyName string, keyType SetupKeyType,
	expiresIn time.Duration, autoGroups []string, usageLimit int, userID string, ephemeral bool) (*SetupKey, error)

CreateSetupKey generates a new setup key with a given name, type, list of groups IDs to auto-assign to peers registered with this key, and adds it to the specified account. A list of autoGroups IDs can be empty.

func (*DefaultAccountManager) CreateUser added in v0.9.8

func (am *DefaultAccountManager) CreateUser(ctx context.Context, accountID, userID string, user *UserInfo) (*UserInfo, error)

CreateUser creates a new user under the given account. Effectively this is a user invite.

func (*DefaultAccountManager) DeleteAccount added in v0.24.4

func (am *DefaultAccountManager) DeleteAccount(ctx context.Context, accountID, userID string) error

DeleteAccount deletes an account and all its users from local store and from the remote IDP if the requester is an admin and account owner

func (*DefaultAccountManager) DeleteGroup

func (am *DefaultAccountManager) DeleteGroup(ctx context.Context, accountId, userId, groupID string) error

DeleteGroup object of the peers.

func (*DefaultAccountManager) DeleteGroups added in v0.28.8

func (am *DefaultAccountManager) DeleteGroups(ctx context.Context, accountId, userId string, groupIDs []string) error

DeleteGroups deletes groups from an account. Note: This function does not acquire the global lock. It is the caller's responsibility to ensure proper locking is in place before invoking this method.

If an error occurs while deleting a group, the function skips it and continues deleting other groups. Errors are collected and returned at the end.

func (*DefaultAccountManager) DeleteNameServerGroup added in v0.9.8

func (am *DefaultAccountManager) DeleteNameServerGroup(ctx context.Context, accountID, nsGroupID, userID string) error

DeleteNameServerGroup deletes nameserver group with nsGroupID

func (*DefaultAccountManager) DeletePAT added in v0.14.5

func (am *DefaultAccountManager) DeletePAT(ctx context.Context, accountID string, initiatorUserID string, targetUserID string, tokenID string) error

DeletePAT deletes a specific PAT from a user

func (*DefaultAccountManager) DeletePeer

func (am *DefaultAccountManager) DeletePeer(ctx context.Context, accountID, peerID, userID string) error

DeletePeer removes peer from the account by its IP

func (*DefaultAccountManager) DeletePolicy added in v0.14.5

func (am *DefaultAccountManager) DeletePolicy(ctx context.Context, accountID, policyID, userID string) error

DeletePolicy from the store

func (*DefaultAccountManager) DeletePostureChecks added in v0.26.0

func (am *DefaultAccountManager) DeletePostureChecks(ctx context.Context, accountID, postureChecksID, userID string) error

func (*DefaultAccountManager) DeleteRegularUsers added in v0.28.8

func (am *DefaultAccountManager) DeleteRegularUsers(ctx context.Context, accountID, initiatorUserID string, targetUserIDs []string) error

DeleteRegularUsers deletes regular users from an account. Note: This function does not acquire the global lock. It is the caller's responsibility to ensure proper locking is in place before invoking this method.

If an error occurs while deleting the user, the function skips it and continues deleting other users. Errors are collected and returned at the end.

func (*DefaultAccountManager) DeleteRoute added in v0.8.9

func (am *DefaultAccountManager) DeleteRoute(ctx context.Context, accountID string, routeID route.ID, userID string) error

DeleteRoute deletes route with routeID

func (*DefaultAccountManager) DeleteSetupKey added in v0.31.0

func (am *DefaultAccountManager) DeleteSetupKey(ctx context.Context, accountID, userID, keyID string) error

DeleteSetupKey removes the setup key from the account

func (*DefaultAccountManager) DeleteUser added in v0.17.0

func (am *DefaultAccountManager) DeleteUser(ctx context.Context, accountID, initiatorUserID string, targetUserID string) error

DeleteUser deletes a user from the given account.

func (*DefaultAccountManager) FindExistingPostureCheck added in v0.28.0

func (am *DefaultAccountManager) FindExistingPostureCheck(accountID string, checks *posture.ChecksDefinition) (*posture.Checks, error)

func (*DefaultAccountManager) GetAccount added in v0.30.0

func (am *DefaultAccountManager) GetAccount(ctx context.Context, accountID string) (*Account, error)

GetAccount returns an account associated with this account ID.

func (*DefaultAccountManager) GetAccountByID added in v0.30.0

func (am *DefaultAccountManager) GetAccountByID(ctx context.Context, accountID string, userID string) (*Account, error)

GetAccountByID returns an account associated with this account ID.

func (*DefaultAccountManager) GetAccountFromPAT added in v0.14.5

func (am *DefaultAccountManager) GetAccountFromPAT(ctx context.Context, token string) (*Account, *User, *PersonalAccessToken, error)

GetAccountFromPAT returns Account and User associated with a personal access token

func (*DefaultAccountManager) GetAccountIDByUserID added in v0.30.0

func (am *DefaultAccountManager) GetAccountIDByUserID(ctx context.Context, userID, domain string) (string, error)

GetAccountIDByUserID retrieves the account ID based on the userID provided. If user does have an account, it returns the user's account ID. If the user doesn't have an account, it creates one using the provided domain. Returns the account ID or an error if none is found or created.

func (*DefaultAccountManager) GetAccountIDForPeerKey added in v0.28.4

func (am *DefaultAccountManager) GetAccountIDForPeerKey(ctx context.Context, peerKey string) (string, error)

func (*DefaultAccountManager) GetAccountIDFromToken added in v0.30.0

func (am *DefaultAccountManager) GetAccountIDFromToken(ctx context.Context, claims jwtclaims.AuthorizationClaims) (string, string, error)

GetAccountIDFromToken returns an account ID associated with this token.

func (*DefaultAccountManager) GetAccountSettings added in v0.30.0

func (am *DefaultAccountManager) GetAccountSettings(ctx context.Context, accountID string, userID string) (*Settings, error)

func (*DefaultAccountManager) GetAllConnectedPeers added in v0.23.9

func (am *DefaultAccountManager) GetAllConnectedPeers() (map[string]struct{}, error)

GetAllConnectedPeers returns connected peers based on peersUpdateManager.GetAllConnectedPeers()

func (*DefaultAccountManager) GetAllGroups added in v0.26.4

func (am *DefaultAccountManager) GetAllGroups(ctx context.Context, accountID, userID string) ([]*nbgroup.Group, error)

GetAllGroups returns all groups in an account

func (*DefaultAccountManager) GetAllPATs added in v0.14.6

func (am *DefaultAccountManager) GetAllPATs(ctx context.Context, accountID string, initiatorUserID string, targetUserID string) ([]*PersonalAccessToken, error)

GetAllPATs returns all PATs for a user

func (*DefaultAccountManager) GetDNSDomain added in v0.10.10

func (am *DefaultAccountManager) GetDNSDomain() string

GetDNSDomain returns the configured dnsDomain

func (*DefaultAccountManager) GetDNSSettings added in v0.12.0

func (am *DefaultAccountManager) GetDNSSettings(ctx context.Context, accountID string, userID string) (*DNSSettings, error)

GetDNSSettings validates a user role and returns the DNS settings for the provided account ID

func (*DefaultAccountManager) GetEvents added in v0.12.0

func (am *DefaultAccountManager) GetEvents(ctx context.Context, accountID, userID string) ([]*activity.Event, error)

GetEvents returns a list of activity events of an account

func (*DefaultAccountManager) GetExternalCacheManager added in v0.24.3

func (am *DefaultAccountManager) GetExternalCacheManager() ExternalCacheManager

func (*DefaultAccountManager) GetGroup

func (am *DefaultAccountManager) GetGroup(ctx context.Context, accountID, groupID, userID string) (*nbgroup.Group, error)

GetGroup returns a specific group by groupID in an account

func (*DefaultAccountManager) GetGroupByName added in v0.25.5

func (am *DefaultAccountManager) GetGroupByName(ctx context.Context, groupName, accountID string) (*nbgroup.Group, error)

GetGroupByName filters all groups in an account by name and returns the one with the most peers

func (*DefaultAccountManager) GetIdpManager added in v0.26.3

func (am *DefaultAccountManager) GetIdpManager() idp.Manager

func (*DefaultAccountManager) GetNameServerGroup added in v0.9.8

func (am *DefaultAccountManager) GetNameServerGroup(ctx context.Context, accountID, userID, nsGroupID string) (*nbdns.NameServerGroup, error)

GetNameServerGroup gets a nameserver group object from account and nameserver group IDs

func (*DefaultAccountManager) GetNetworkMap

func (am *DefaultAccountManager) GetNetworkMap(ctx context.Context, peerID string) (*NetworkMap, error)

GetNetworkMap returns Network map for a given peer (omits original peer from the Peers result)

func (*DefaultAccountManager) GetOrCreateAccountByUser

func (am *DefaultAccountManager) GetOrCreateAccountByUser(ctx context.Context, userID, domain string) (*Account, error)

GetOrCreateAccountByUser returns an existing account for a given user id or creates a new one if doesn't exist

func (*DefaultAccountManager) GetPAT added in v0.14.6

func (am *DefaultAccountManager) GetPAT(ctx context.Context, accountID string, initiatorUserID string, targetUserID string, tokenID string) (*PersonalAccessToken, error)

GetPAT returns a specific PAT from a user

func (*DefaultAccountManager) GetPeer

func (am *DefaultAccountManager) GetPeer(ctx context.Context, accountID, peerID, userID string) (*nbpeer.Peer, error)

GetPeer for a given accountID, peerID and userID error if not found.

func (*DefaultAccountManager) GetPeerNetwork added in v0.8.0

func (am *DefaultAccountManager) GetPeerNetwork(ctx context.Context, peerID string) (*Network, error)

GetPeerNetwork returns the Network for a given peer

func (*DefaultAccountManager) GetPeers added in v0.10.5

func (am *DefaultAccountManager) GetPeers(ctx context.Context, accountID, userID string) ([]*nbpeer.Peer, error)

GetPeers returns a list of peers under the given account filtering out peers that do not belong to a user if the current user is not an admin.

func (*DefaultAccountManager) GetPolicy added in v0.14.5

func (am *DefaultAccountManager) GetPolicy(ctx context.Context, accountID, policyID, userID string) (*Policy, error)

GetPolicy from the store

func (*DefaultAccountManager) GetPostureChecks added in v0.26.0

func (am *DefaultAccountManager) GetPostureChecks(ctx context.Context, accountID, postureChecksID, userID string) (*posture.Checks, error)

func (*DefaultAccountManager) GetRoute added in v0.8.9

func (am *DefaultAccountManager) GetRoute(ctx context.Context, accountID string, routeID route.ID, userID string) (*route.Route, error)

GetRoute gets a route object from account and route IDs

func (*DefaultAccountManager) GetSetupKey added in v0.9.2

func (am *DefaultAccountManager) GetSetupKey(ctx context.Context, accountID, userID, keyID string) (*SetupKey, error)

GetSetupKey looks up a SetupKey by KeyID, returns NotFound error if not found.

func (*DefaultAccountManager) GetUser added in v0.20.0

GetUser looks up a user by provided authorization claims. It will also create an account if didn't exist for this user before.

func (*DefaultAccountManager) GetUserByID added in v0.30.0

func (am *DefaultAccountManager) GetUserByID(ctx context.Context, id string) (*User, error)

func (*DefaultAccountManager) GetUsersFromAccount

func (am *DefaultAccountManager) GetUsersFromAccount(ctx context.Context, accountID, userID string) ([]*UserInfo, error)

GetUsersFromAccount performs a batched request for users from IDP by account ID apply filter on what data to return based on provided user role.

func (*DefaultAccountManager) GetValidatedPeers added in v0.26.5

func (am *DefaultAccountManager) GetValidatedPeers(account *Account) (map[string]struct{}, error)

func (*DefaultAccountManager) GroupAddPeer

func (am *DefaultAccountManager) GroupAddPeer(ctx context.Context, accountID, groupID, peerID string) error

GroupAddPeer appends peer to the group

func (*DefaultAccountManager) GroupDeletePeer

func (am *DefaultAccountManager) GroupDeletePeer(ctx context.Context, accountID, groupID, peerID string) error

GroupDeletePeer removes peer from the group

func (*DefaultAccountManager) GroupValidation added in v0.26.5

func (am *DefaultAccountManager) GroupValidation(ctx context.Context, accountId string, groups []string) (bool, error)

func (*DefaultAccountManager) HasConnectedChannel added in v0.24.4

func (am *DefaultAccountManager) HasConnectedChannel(peerID string) bool

HasConnectedChannel returns true if peers has channel in update manager, otherwise false

func (*DefaultAccountManager) InviteUser added in v0.21.9

func (am *DefaultAccountManager) InviteUser(ctx context.Context, accountID string, initiatorUserID string, targetUserID string) error

InviteUser resend invitations to users who haven't activated their accounts prior to the expiration period.

func (*DefaultAccountManager) ListGroups

func (am *DefaultAccountManager) ListGroups(ctx context.Context, accountID string) ([]*nbgroup.Group, error)

ListGroups objects of the peers

func (*DefaultAccountManager) ListNameServerGroups added in v0.9.8

func (am *DefaultAccountManager) ListNameServerGroups(ctx context.Context, accountID string, userID string) ([]*nbdns.NameServerGroup, error)

ListNameServerGroups returns a list of nameserver groups from account

func (*DefaultAccountManager) ListPolicies added in v0.14.5

func (am *DefaultAccountManager) ListPolicies(ctx context.Context, accountID, userID string) ([]*Policy, error)

ListPolicies from the store

func (*DefaultAccountManager) ListPostureChecks added in v0.26.0

func (am *DefaultAccountManager) ListPostureChecks(ctx context.Context, accountID, userID string) ([]*posture.Checks, error)

func (*DefaultAccountManager) ListRoutes added in v0.8.9

func (am *DefaultAccountManager) ListRoutes(ctx context.Context, accountID, userID string) ([]*route.Route, error)

ListRoutes returns a list of routes from account

func (*DefaultAccountManager) ListSetupKeys added in v0.9.2

func (am *DefaultAccountManager) ListSetupKeys(ctx context.Context, accountID, userID string) ([]*SetupKey, error)

ListSetupKeys returns a list of all setup keys of the account

func (*DefaultAccountManager) ListUsers added in v0.24.3

func (am *DefaultAccountManager) ListUsers(ctx context.Context, accountID string) ([]*User, error)

ListUsers returns lists of all users under the account. It doesn't populate user information such as email or name.

func (*DefaultAccountManager) LoginPeer added in v0.14.3

LoginPeer logs in or registers a peer. If peer doesn't exist the function checks whether a setup key or a user is present and registers a new peer if so.

func (*DefaultAccountManager) MarkPATUsed added in v0.15.0

func (am *DefaultAccountManager) MarkPATUsed(ctx context.Context, tokenID string) error

MarkPATUsed marks a personal access token as used

func (*DefaultAccountManager) MarkPeerConnected

func (am *DefaultAccountManager) MarkPeerConnected(ctx context.Context, peerPubKey string, connected bool, realIP net.IP, account *Account) error

MarkPeerConnected marks peer as connected (true) or disconnected (false)

func (*DefaultAccountManager) OnPeerDisconnected added in v0.28.7

func (am *DefaultAccountManager) OnPeerDisconnected(ctx context.Context, accountID string, peerPubKey string) error

func (*DefaultAccountManager) SaveDNSSettings added in v0.12.0

func (am *DefaultAccountManager) SaveDNSSettings(ctx context.Context, accountID string, userID string, dnsSettingsToSave *DNSSettings) error

SaveDNSSettings validates a user role and updates the account's DNS settings

func (*DefaultAccountManager) SaveGroup

func (am *DefaultAccountManager) SaveGroup(ctx context.Context, accountID, userID string, newGroup *nbgroup.Group) error

SaveGroup object of the peers

func (*DefaultAccountManager) SaveGroups added in v0.28.5

func (am *DefaultAccountManager) SaveGroups(ctx context.Context, accountID, userID string, newGroups []*nbgroup.Group) error

SaveGroups adds new groups to the account. Note: This function does not acquire the global lock. It is the caller's responsibility to ensure proper locking is in place before invoking this method.

func (*DefaultAccountManager) SaveNameServerGroup added in v0.9.8

func (am *DefaultAccountManager) SaveNameServerGroup(ctx context.Context, accountID, userID string, nsGroupToSave *nbdns.NameServerGroup) error

SaveNameServerGroup saves nameserver group

func (*DefaultAccountManager) SaveOrAddUser added in v0.24.3

func (am *DefaultAccountManager) SaveOrAddUser(ctx context.Context, accountID, initiatorUserID string, update *User, addIfNotExists bool) (*UserInfo, error)

SaveOrAddUser updates the given user. If addIfNotExists is set to true it will add user when no exist Only User.AutoGroups, User.Role, and User.Blocked fields are allowed to be updated for now.

func (*DefaultAccountManager) SaveOrAddUsers added in v0.28.5

func (am *DefaultAccountManager) SaveOrAddUsers(ctx context.Context, accountID, initiatorUserID string, updates []*User, addIfNotExists bool) ([]*UserInfo, error)

SaveOrAddUsers updates existing users or adds new users to the account. Note: This function does not acquire the global lock. It is the caller's responsibility to ensure proper locking is in place before invoking this method.

func (*DefaultAccountManager) SavePolicy added in v0.14.5

func (am *DefaultAccountManager) SavePolicy(ctx context.Context, accountID, userID string, policy *Policy, isUpdate bool) error

SavePolicy in the store

func (*DefaultAccountManager) SavePostureChecks added in v0.26.0

func (am *DefaultAccountManager) SavePostureChecks(ctx context.Context, accountID, userID string, postureChecks *posture.Checks) error

func (*DefaultAccountManager) SaveRoute added in v0.8.9

func (am *DefaultAccountManager) SaveRoute(ctx context.Context, accountID, userID string, routeToSave *route.Route) error

SaveRoute saves route

func (*DefaultAccountManager) SaveSetupKey added in v0.9.2

func (am *DefaultAccountManager) SaveSetupKey(ctx context.Context, accountID string, keyToSave *SetupKey, userID string) (*SetupKey, error)

SaveSetupKey saves the provided SetupKey to the database overriding the existing one. Due to the unique nature of a SetupKey certain properties must not be overwritten (e.g. the key itself, creation date, ID, etc). These properties are overwritten: Name, AutoGroups, Revoked. The rest is copied from the existing key.

func (*DefaultAccountManager) SaveUser added in v0.9.4

func (am *DefaultAccountManager) SaveUser(ctx context.Context, accountID, initiatorUserID string, update *User) (*UserInfo, error)

SaveUser saves updates to the given user. If the user doesn't exist, it will throw status.NotFound error.

func (*DefaultAccountManager) StoreEvent added in v0.24.3

func (am *DefaultAccountManager) StoreEvent(ctx context.Context, initiatorID, targetID, accountID string, activityID activity.ActivityDescriber, meta map[string]any)

func (*DefaultAccountManager) SyncAndMarkPeer added in v0.27.5

func (am *DefaultAccountManager) SyncAndMarkPeer(ctx context.Context, accountID string, peerPubKey string, meta nbpeer.PeerSystemMeta, realIP net.IP) (*nbpeer.Peer, *NetworkMap, []*posture.Checks, error)

func (*DefaultAccountManager) SyncPeer added in v0.14.3

func (am *DefaultAccountManager) SyncPeer(ctx context.Context, sync PeerSync, account *Account) (*nbpeer.Peer, *NetworkMap, []*posture.Checks, error)

SyncPeer checks whether peer is eligible for receiving NetworkMap (authenticated) and returns its NetworkMap if eligible

func (*DefaultAccountManager) SyncPeerMeta added in v0.28.0

func (am *DefaultAccountManager) SyncPeerMeta(ctx context.Context, peerPubKey string, meta nbpeer.PeerSystemMeta) error

func (*DefaultAccountManager) UpdateAccountSettings added in v0.14.0

func (am *DefaultAccountManager) UpdateAccountSettings(ctx context.Context, accountID, userID string, newSettings *Settings) (*Account, error)

UpdateAccountSettings updates Account settings. Only users with role UserRoleAdmin can update the account. User that performs the update has to belong to the account. Returns an updated Account

func (*DefaultAccountManager) UpdateIntegratedValidatorGroups added in v0.26.5

func (am *DefaultAccountManager) UpdateIntegratedValidatorGroups(ctx context.Context, accountID string, userID string, groups []string) error

UpdateIntegratedValidatorGroups updates the integrated validator groups for a specified account. It retrieves the account associated with the provided userID, then updates the integrated validator groups with the provided list of group ids. The updated account is then saved.

Parameters:

  • accountID: The ID of the account for which integrated validator groups are to be updated.
  • userID: The ID of the user whose account is being updated.
  • groups: A slice of strings representing the ids of integrated validator groups to be updated.

Returns:

  • error: An error if any occurred during the process, otherwise returns nil

func (*DefaultAccountManager) UpdatePeer added in v0.8.0

func (am *DefaultAccountManager) UpdatePeer(ctx context.Context, accountID, userID string, update *nbpeer.Peer) (*nbpeer.Peer, error)

UpdatePeer updates peer. Only Peer.Name, Peer.SSHEnabled, Peer.LoginExpirationEnabled and Peer.InactivityExpirationEnabled can be updated.

type DefaultScheduler added in v0.14.2

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

DefaultScheduler is a generic structure that allows to schedule jobs (functions) to run in the future and cancel them.

func NewDefaultScheduler added in v0.14.2

func NewDefaultScheduler() *DefaultScheduler

NewDefaultScheduler creates an instance of a DefaultScheduler

func (*DefaultScheduler) Cancel added in v0.14.2

func (wm *DefaultScheduler) Cancel(ctx context.Context, IDs []string)

Cancel cancels the scheduled job by ID if present. If job wasn't found the function returns false.

func (*DefaultScheduler) Schedule added in v0.14.2

func (wm *DefaultScheduler) Schedule(ctx context.Context, in time.Duration, ID string, job func() (nextRunIn time.Duration, reschedule bool))

Schedule a job to run in some time in the future. If job returns true then it will be scheduled one more time. If job with the provided ID already exists, a new one won't be scheduled.

type DeviceAuthorizationFlow

type DeviceAuthorizationFlow struct {
	Provider       string
	ProviderConfig ProviderConfig
}

DeviceAuthorizationFlow represents Device Authorization Flow information that can be used by the client to login initiate a Oauth 2.0 device authorization grant flow see https://datatracker.ietf.org/doc/html/rfc8628

type EphemeralManager added in v0.23.0

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

EphemeralManager keep a list of ephemeral peers. After ephemeralLifeTime inactivity the peer will be deleted automatically. Inactivity means the peer disconnected from the Management server.

func NewEphemeralManager added in v0.23.0

func NewEphemeralManager(store Store, accountManager AccountManager) *EphemeralManager

NewEphemeralManager instantiate new EphemeralManager

func (*EphemeralManager) LoadInitialPeers added in v0.23.0

func (e *EphemeralManager) LoadInitialPeers(ctx context.Context)

LoadInitialPeers load from the database the ephemeral type of peers and schedule a cleanup procedure to the head of the linked list (to the most deprecated peer). At the end of cleanup it schedules the next cleanup to the new head.

func (*EphemeralManager) OnPeerConnected added in v0.23.0

func (e *EphemeralManager) OnPeerConnected(ctx context.Context, peer *nbpeer.Peer)

OnPeerConnected remove the peer from the linked list of ephemeral peers. Because it has been called when the peer is active the manager will not delete it while it is active.

func (*EphemeralManager) OnPeerDisconnected added in v0.23.0

func (e *EphemeralManager) OnPeerDisconnected(ctx context.Context, peer *nbpeer.Peer)

OnPeerDisconnected add the peer to the linked list of ephemeral peers. Because of the peer is inactive it will be deleted after the ephemeralLifeTime period.

func (*EphemeralManager) Stop added in v0.23.0

func (e *EphemeralManager) Stop()

Stop timer

type ExternalCacheManager added in v0.24.3

type ExternalCacheManager cache.CacheInterface[*idp.UserData]

type FileStore

type FileStore struct {
	Accounts                map[string]*Account
	SetupKeyID2AccountID    map[string]string `json:"-"`
	PeerKeyID2AccountID     map[string]string `json:"-"`
	PeerID2AccountID        map[string]string `json:"-"`
	UserID2AccountID        map[string]string `json:"-"`
	PrivateDomain2AccountID map[string]string `json:"-"`
	HashedPAT2TokenID       map[string]string `json:"-"`
	TokenID2UserID          map[string]string `json:"-"`
	InstallationID          string
	// contains filtered or unexported fields
}

FileStore represents an account storage backed by a file persisted to disk

func NewFileStore added in v0.10.7

func NewFileStore(ctx context.Context, dataDir string, metrics telemetry.AppMetrics) (*FileStore, error)

NewFileStore restores a store from the file located in the datadir

func (*FileStore) Close added in v0.10.7

func (s *FileStore) Close(ctx context.Context) error

Close the FileStore persisting data to disk

func (*FileStore) GetAllAccounts

func (s *FileStore) GetAllAccounts(_ context.Context) (all []*Account)

GetAllAccounts returns all accounts

func (*FileStore) GetStoreEngine added in v0.24.0

func (s *FileStore) GetStoreEngine() StoreEngine

GetStoreEngine returns FileStoreEngine

type FirewallRule added in v0.14.5

type FirewallRule struct {
	// PeerIP of the peer
	PeerIP string

	// Direction of the traffic
	Direction int

	// Action of the traffic
	Action string

	// Protocol of the traffic
	Protocol string

	// Port of the traffic
	Port string
}

FirewallRule is a rule of the firewall.

type GRPCServer added in v0.8.5

type GRPCServer struct {
	proto.UnimplementedManagementServiceServer
	// contains filtered or unexported fields
}

GRPCServer an instance of a Management gRPC API server

func NewServer

func NewServer(
	ctx context.Context,
	config *Config,
	accountManager AccountManager,
	peersUpdateManager *PeersUpdateManager,
	secretsManager SecretsManager,
	appMetrics telemetry.AppMetrics,
	ephemeralManager *EphemeralManager,
) (*GRPCServer, error)

NewServer creates a new Management server

func (*GRPCServer) GetDeviceAuthorizationFlow added in v0.8.5

func (s *GRPCServer) GetDeviceAuthorizationFlow(ctx context.Context, req *proto.EncryptedMessage) (*proto.EncryptedMessage, error)

GetDeviceAuthorizationFlow returns a device authorization flow information This is used for initiating an Oauth 2 device authorization grant flow which will be used by our clients to Login

func (*GRPCServer) GetPKCEAuthorizationFlow added in v0.22.0

func (s *GRPCServer) GetPKCEAuthorizationFlow(ctx context.Context, req *proto.EncryptedMessage) (*proto.EncryptedMessage, error)

GetPKCEAuthorizationFlow returns a pkce authorization flow information This is used for initiating an Oauth 2 pkce authorization grant flow which will be used by our clients to Login

func (*GRPCServer) GetServerKey added in v0.8.5

func (s *GRPCServer) GetServerKey(ctx context.Context, req *proto.Empty) (*proto.ServerKeyResponse, error)

func (*GRPCServer) IsHealthy added in v0.8.5

func (s *GRPCServer) IsHealthy(ctx context.Context, req *proto.Empty) (*proto.Empty, error)

IsHealthy indicates whether the service is healthy

func (*GRPCServer) Login added in v0.8.5

Login endpoint first checks whether peer is registered under any account In case it is, the login is successful In case it isn't, the endpoint checks whether setup key is provided within the request and tries to register a peer. In case of the successful registration login is also successful

func (*GRPCServer) Sync added in v0.8.5

Sync validates the existence of a connecting peer, sends an initial state (all available for the connecting peers) and notifies the connected peer of any updates (e.g. new peers under the same account)

func (*GRPCServer) SyncMeta added in v0.28.0

func (s *GRPCServer) SyncMeta(ctx context.Context, req *proto.EncryptedMessage) (*proto.Empty, error)

SyncMeta endpoint is used to synchronize peer's system metadata and notifies the connected, peer's under the same account of any updates.

type GroupLinkError added in v0.21.9

type GroupLinkError struct {
	Resource string
	Name     string
}

func (*GroupLinkError) Error added in v0.21.9

func (e *GroupLinkError) Error() string

type Host

type Host struct {
	Proto Protocol
	// URI e.g. turns://stun.wiretrustee.com:4430 or signal.wiretrustee.com:10000
	URI      string
	Username string
	Password string
}

Host represents a Wiretrustee host (e.g. STUN, TURN, Signal)

type HttpServerConfig

type HttpServerConfig struct {
	LetsEncryptDomain string
	// CertFile is the location of the certificate
	CertFile string
	// CertKey is the location of the certificate private key
	CertKey string
	// AuthAudience identifies the recipients that the JWT is intended for (aud in JWT)
	AuthAudience string
	// AuthIssuer identifies principal that issued the JWT
	AuthIssuer string
	// AuthUserIDClaim is the name of the claim that used as user ID
	AuthUserIDClaim string
	// AuthKeysLocation is a location of JWT key set containing the public keys used to verify JWT
	AuthKeysLocation string
	// OIDCConfigEndpoint is the endpoint of an IDP manager to get OIDC configuration
	OIDCConfigEndpoint string
	// IdpSignKeyRefreshEnabled identifies the signing key is currently being rotated or not
	IdpSignKeyRefreshEnabled bool
	// Extra audience
	ExtraAuthAudience string
}

HttpServerConfig is a config of the HTTP Management service server

type LockingStrength added in v0.29.3

type LockingStrength string
const (
	LockingStrengthUpdate      LockingStrength = "UPDATE"        // Strongest lock, preventing any changes by other transactions until your transaction completes.
	LockingStrengthShare       LockingStrength = "SHARE"         // Allows reading but prevents changes by other transactions.
	LockingStrengthNoKeyUpdate LockingStrength = "NO KEY UPDATE" // Similar to UPDATE but allows changes to related rows.
	LockingStrengthKeyShare    LockingStrength = "KEY SHARE"     // Protects against changes to primary/unique keys but allows other updates.
)

type MockScheduler added in v0.14.2

type MockScheduler struct {
	CancelFunc   func(ctx context.Context, IDs []string)
	ScheduleFunc func(ctx context.Context, in time.Duration, ID string, job func() (nextRunIn time.Duration, reschedule bool))
}

MockScheduler is a mock implementation of Scheduler

func (*MockScheduler) Cancel added in v0.14.2

func (mock *MockScheduler) Cancel(ctx context.Context, IDs []string)

Cancel mocks the Cancel function of the Scheduler interface

func (*MockScheduler) Schedule added in v0.14.2

func (mock *MockScheduler) Schedule(ctx context.Context, in time.Duration, ID string, job func() (nextRunIn time.Duration, reschedule bool))

Schedule mocks the Schedule function of the Scheduler interface

type Network

type Network struct {
	Identifier string    `json:"id"`
	Net        net.IPNet `gorm:"serializer:json"`
	Dns        string
	// Serial is an ID that increments by 1 when any change to the network happened (e.g. new peer has been added).
	// Used to synchronize state to the client apps.
	Serial uint64
	// contains filtered or unexported fields
}

func NewNetwork

func NewNetwork() *Network

NewNetwork creates a new Network initializing it with a Serial=0 It takes a random /16 subnet from 100.64.0.0/10 (64 different subnets)

func (*Network) Copy

func (n *Network) Copy() *Network

func (*Network) CurrentSerial

func (n *Network) CurrentSerial() uint64

CurrentSerial returns the Network.Serial of the network (latest state id)

func (*Network) IncSerial

func (n *Network) IncSerial()

IncSerial increments Serial by 1 reflecting that the network state has been changed

type NetworkMap

type NetworkMap struct {
	Peers               []*nbpeer.Peer
	Network             *Network
	Routes              []*route.Route
	DNSConfig           nbdns.Config
	OfflinePeers        []*nbpeer.Peer
	FirewallRules       []*FirewallRule
	RoutesFirewallRules []*RouteFirewallRule
}

type PKCEAuthorizationFlow added in v0.22.0

type PKCEAuthorizationFlow struct {
	ProviderConfig ProviderConfig
}

PKCEAuthorizationFlow represents Authorization Code Flow information that can be used by the client to login initiate a Oauth 2.0 authorization code grant flow with Proof Key for Code Exchange (PKCE). See https://datatracker.ietf.org/doc/html/rfc7636

type PeerLogin added in v0.14.3

type PeerLogin struct {
	// WireGuardPubKey is a peers WireGuard public key
	WireGuardPubKey string
	// SSHKey is a peer's ssh key. Can be empty (e.g., old version do not provide it, or this feature is disabled)
	SSHKey string
	// Meta is the system information passed by peer, must be always present.
	Meta nbpeer.PeerSystemMeta
	// UserID indicates that JWT was used to log in, and it was valid. Can be empty when SetupKey is used or auth is not required.
	UserID string
	// SetupKey references to a server.SetupKey to log in. Can be empty when UserID is used or auth is not required.
	SetupKey string
	// ConnectionIP is the real IP of the peer
	ConnectionIP net.IP
}

PeerLogin used as a data object between the gRPC API and AccountManager on Login request.

type PeerSync added in v0.14.3

type PeerSync struct {
	// WireGuardPubKey is a peers WireGuard public key
	WireGuardPubKey string
	// Meta is the system information passed by peer, must be always present
	Meta nbpeer.PeerSystemMeta
	// UpdateAccountPeers indicate updating account peers,
	// which occurs when the peer's metadata is updated
	UpdateAccountPeers bool
}

PeerSync used as a data object between the gRPC API and AccountManager on Sync request.

type PeersUpdateManager

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

func NewPeersUpdateManager

func NewPeersUpdateManager(metrics telemetry.AppMetrics) *PeersUpdateManager

NewPeersUpdateManager returns a new instance of PeersUpdateManager

func (*PeersUpdateManager) CloseChannel

func (p *PeersUpdateManager) CloseChannel(ctx context.Context, peerID string)

CloseChannel closes updates channel of a given peer

func (*PeersUpdateManager) CloseChannels added in v0.14.2

func (p *PeersUpdateManager) CloseChannels(ctx context.Context, peerIDs []string)

CloseChannels closes updates channel for each given peer

func (*PeersUpdateManager) CreateChannel

func (p *PeersUpdateManager) CreateChannel(ctx context.Context, peerID string) chan *UpdateMessage

CreateChannel creates a go channel for a given peer used to deliver updates relevant to the peer.

func (*PeersUpdateManager) GetAllConnectedPeers added in v0.10.0

func (p *PeersUpdateManager) GetAllConnectedPeers() map[string]struct{}

GetAllConnectedPeers returns a copy of the connected peers map

func (*PeersUpdateManager) HasChannel added in v0.24.4

func (p *PeersUpdateManager) HasChannel(peerID string) bool

HasChannel returns true if peers has channel in update manager, otherwise false

func (*PeersUpdateManager) SendUpdate

func (p *PeersUpdateManager) SendUpdate(ctx context.Context, peerID string, update *UpdateMessage)

SendUpdate sends update message to the peer's channel

type PersonalAccessToken added in v0.14.5

type PersonalAccessToken struct {
	ID string `gorm:"primaryKey"`
	// User is a reference to Account that this object belongs
	UserID         string `gorm:"index"`
	Name           string
	HashedToken    string
	ExpirationDate time.Time
	// scope could be added in future
	CreatedBy string
	CreatedAt time.Time
	LastUsed  time.Time
}

PersonalAccessToken holds all information about a PAT including a hashed version of it for verification

func (*PersonalAccessToken) Copy added in v0.22.7

type PersonalAccessTokenGenerated added in v0.14.6

type PersonalAccessTokenGenerated struct {
	PlainToken string
	PersonalAccessToken
}

PersonalAccessTokenGenerated holds the new PersonalAccessToken and the plain text version of it

func CreateNewPAT added in v0.14.5

func CreateNewPAT(name string, expirationInDays int, createdBy string) (*PersonalAccessTokenGenerated, error)

CreateNewPAT will generate a new PersonalAccessToken that can be assigned to a User. Additionally, it will return the token in plain text once, to give to the user and only save a hashed version

type Policy added in v0.14.5

type Policy struct {
	// ID of the policy'
	ID string `gorm:"primaryKey"`

	// AccountID is a reference to Account that this object belongs
	AccountID string `json:"-" gorm:"index"`

	// Name of the Policy
	Name string

	// Description of the policy visible in the UI
	Description string

	// Enabled status of the policy
	Enabled bool

	// Rules of the policy
	Rules []*PolicyRule `gorm:"foreignKey:PolicyID;references:id;constraint:OnDelete:CASCADE;"`

	// SourcePostureChecks are ID references to Posture checks for policy source groups
	SourcePostureChecks []string `gorm:"serializer:json"`
}

Policy of the Rego query

func (*Policy) Copy added in v0.14.5

func (p *Policy) Copy() *Policy

Copy returns a copy of the policy.

func (*Policy) EventMeta added in v0.14.5

func (p *Policy) EventMeta() map[string]any

EventMeta returns activity event meta related to this policy

func (*Policy) UpgradeAndFix added in v0.21.0

func (p *Policy) UpgradeAndFix()

UpgradeAndFix different version of policies to latest version

type PolicyRule added in v0.14.5

type PolicyRule struct {
	// ID of the policy rule
	ID string `gorm:"primaryKey"`

	// PolicyID is a reference to Policy that this object belongs
	PolicyID string `json:"-" gorm:"index"`

	// Name of the rule visible in the UI
	Name string

	// Description of the rule visible in the UI
	Description string

	// Enabled status of rule in the system
	Enabled bool

	// Action policy accept or drops packets
	Action PolicyTrafficActionType

	// Destinations policy destination groups
	Destinations []string `gorm:"serializer:json"`

	// Sources policy source groups
	Sources []string `gorm:"serializer:json"`

	// Bidirectional define if the rule is applicable in both directions, sources, and destinations
	Bidirectional bool

	// Protocol type of the traffic
	Protocol PolicyRuleProtocolType

	// Ports or it ranges list
	Ports []string `gorm:"serializer:json"`

	// PortRanges a list of port ranges.
	PortRanges []RulePortRange `gorm:"serializer:json"`
}

PolicyRule is the metadata of the policy

func (*PolicyRule) Copy added in v0.14.5

func (pm *PolicyRule) Copy() *PolicyRule

Copy returns a copy of a policy rule

type PolicyRuleDirection added in v0.21.0

type PolicyRuleDirection string

PolicyRuleDirection direction of traffic

type PolicyRuleProtocolType added in v0.21.0

type PolicyRuleProtocolType string

PolicyRuleProtocolType type of traffic

type PolicyTrafficActionType added in v0.14.5

type PolicyTrafficActionType string

PolicyTrafficActionType action type for the firewall

type PolicyUpdateOperation added in v0.14.5

type PolicyUpdateOperation struct {
	Type   PolicyUpdateOperationType
	Values []string
}

PolicyUpdateOperation operation object with type and values to be applied

type PolicyUpdateOperationType added in v0.14.5

type PolicyUpdateOperationType int

PolicyUpdateOperationType operation type

type Protocol

type Protocol string

Protocol type

type Provider

type Provider string

Provider authorization flow type

type ProviderConfig

type ProviderConfig struct {
	// ClientID An IDP application client id
	ClientID string
	// ClientSecret An IDP application client secret
	ClientSecret string
	// Domain An IDP API domain
	// Deprecated. Use TokenEndpoint and DeviceAuthEndpoint
	Domain string
	// Audience An Audience for to authorization validation
	Audience string
	// TokenEndpoint is the endpoint of an IDP manager where clients can obtain access token
	TokenEndpoint string
	// DeviceAuthEndpoint is the endpoint of an IDP manager where clients can obtain device authorization code
	DeviceAuthEndpoint string
	// AuthorizationEndpoint is the endpoint of an IDP manager where clients can obtain authorization code
	AuthorizationEndpoint string
	// Scopes provides the scopes to be included in the token request
	Scope string
	// UseIDToken indicates if the id token should be used for authentication
	UseIDToken bool
	// RedirectURL handles authorization code from IDP manager
	RedirectURLs []string
}

ProviderConfig has all attributes needed to initiate a device/pkce authorization flow

type Relay added in v0.29.0

type Relay struct {
	Addresses      []string
	CredentialsTTL util.Duration
	Secret         string
}

type ReverseProxy added in v0.25.8

type ReverseProxy struct {
	// TrustedHTTPProxies represents a list of trusted HTTP proxies by their IP prefixes.
	// When extracting the real IP address from request headers, the middleware will verify
	// if the peer's address falls within one of these trusted IP prefixes.
	TrustedHTTPProxies []netip.Prefix

	// TrustedHTTPProxiesCount specifies the count of trusted HTTP proxies between the internet
	// and the server. When using the trusted proxy count method to extract the real IP address,
	// the middleware will search the X-Forwarded-For IP list from the rightmost by this count
	// minus one.
	TrustedHTTPProxiesCount uint

	// TrustedPeers represents a list of trusted peers by their IP prefixes.
	// These peers are considered trustworthy by the gRPC server operator,
	// and the middleware will attempt to extract the real IP address from
	// request headers if the peer's address falls within one of these
	// trusted IP prefixes.
	TrustedPeers []netip.Prefix
}

ReverseProxy contains reverse proxy configuration in front of management.

type RouteFirewallRule added in v0.30.0

type RouteFirewallRule struct {
	// SourceRanges IP ranges of the routing peers.
	SourceRanges []string

	// Action of the traffic when the rule is applicable
	Action string

	// Destination a network prefix for the routed traffic
	Destination string

	// Protocol of the traffic
	Protocol string

	// Port of the traffic
	Port uint16

	// PortRange represents the range of ports for a firewall rule
	PortRange RulePortRange

	// isDynamic indicates whether the rule is for DNS routing
	IsDynamic bool
}

RouteFirewallRule a firewall rule applicable for a routed network.

type RulePortRange added in v0.30.0

type RulePortRange struct {
	Start uint16
	End   uint16
}

RulePortRange represents a range of ports for a firewall rule.

type Scheduler added in v0.14.2

type Scheduler interface {
	Cancel(ctx context.Context, IDs []string)
	Schedule(ctx context.Context, in time.Duration, ID string, job func() (nextRunIn time.Duration, reschedule bool))
}

Scheduler is an interface which implementations can schedule and cancel jobs

type SecretsManager added in v0.29.0

type SecretsManager interface {
	GenerateTurnToken() (*Token, error)
	GenerateRelayToken() (*Token, error)
	SetupRefresh(ctx context.Context, peerKey string)
	CancelRefresh(peerKey string)
}

SecretsManager used to manage TURN and relay secrets

type Settings added in v0.14.0

type Settings struct {
	// PeerLoginExpirationEnabled globally enables or disables peer login expiration
	PeerLoginExpirationEnabled bool

	// PeerLoginExpiration is a setting that indicates when peer login expires.
	// Applies to all peers that have Peer.LoginExpirationEnabled set to true.
	PeerLoginExpiration time.Duration

	// PeerInactivityExpirationEnabled globally enables or disables peer inactivity expiration
	PeerInactivityExpirationEnabled bool

	// PeerInactivityExpiration is a setting that indicates when peer inactivity expires.
	// Applies to all peers that have Peer.PeerInactivityExpirationEnabled set to true.
	PeerInactivityExpiration time.Duration

	// RegularUsersViewBlocked allows to block regular users from viewing even their own peers and some UI elements
	RegularUsersViewBlocked bool

	// GroupsPropagationEnabled allows to propagate auto groups from the user to the peer
	GroupsPropagationEnabled bool

	// JWTGroupsEnabled allows extract groups from JWT claim, which name defined in the JWTGroupsClaimName
	// and add it to account groups.
	JWTGroupsEnabled bool

	// JWTGroupsClaimName from which we extract groups name to add it to account groups
	JWTGroupsClaimName string

	// JWTAllowGroups list of groups to which users are allowed access
	JWTAllowGroups []string `gorm:"serializer:json"`

	// Extra is a dictionary of Account settings
	Extra *account.ExtraSettings `gorm:"embedded;embeddedPrefix:extra_"`
}

Settings represents Account settings structure that can be modified via API and Dashboard

func (*Settings) Copy added in v0.14.0

func (s *Settings) Copy() *Settings

Copy copies the Settings struct

type SetupKey

type SetupKey struct {
	Id string
	// AccountID is a reference to Account that this object belongs
	AccountID string `json:"-" gorm:"index"`
	Key       string
	KeySecret string
	Name      string
	Type      SetupKeyType
	CreatedAt time.Time
	ExpiresAt time.Time
	UpdatedAt time.Time `gorm:"autoUpdateTime:false"`
	// Revoked indicates whether the key was revoked or not (we don't remove them for tracking purposes)
	Revoked bool
	// UsedTimes indicates how many times the key was used
	UsedTimes int
	// LastUsed last time the key was used for peer registration
	LastUsed time.Time
	// AutoGroups is a list of Group IDs that are auto assigned to a Peer when it uses this key to register
	AutoGroups []string `gorm:"serializer:json"`
	// UsageLimit indicates the number of times this key can be used to enroll a machine.
	// The value of 0 indicates the unlimited usage.
	UsageLimit int
	// Ephemeral indicate if the peers will be ephemeral or not
	Ephemeral bool
}

SetupKey represents a pre-authorized key used to register machines (peers)

func GenerateDefaultSetupKey

func GenerateDefaultSetupKey() (*SetupKey, string)

GenerateDefaultSetupKey generates a default reusable setup key with an unlimited usage and 30 days expiration

func GenerateSetupKey

func GenerateSetupKey(name string, t SetupKeyType, validFor time.Duration, autoGroups []string,
	usageLimit int, ephemeral bool) (*SetupKey, string)

GenerateSetupKey generates a new setup key

func (*SetupKey) Copy

func (key *SetupKey) Copy() *SetupKey

Copy copies SetupKey to a new object

func (*SetupKey) EventMeta added in v0.12.0

func (key *SetupKey) EventMeta() map[string]any

EventMeta returns activity event meta related to the setup key

func (*SetupKey) IncrementUsage

func (key *SetupKey) IncrementUsage() *SetupKey

IncrementUsage makes a copy of a key, increments the UsedTimes by 1 and sets LastUsed to now

func (*SetupKey) IsExpired

func (key *SetupKey) IsExpired() bool

IsExpired if key was expired

func (*SetupKey) IsOverUsed

func (key *SetupKey) IsOverUsed() bool

IsOverUsed if the key was used too many times. SetupKey.UsageLimit == 0 indicates the unlimited usage.

func (*SetupKey) IsRevoked

func (key *SetupKey) IsRevoked() bool

IsRevoked if key was revoked

func (*SetupKey) IsValid

func (key *SetupKey) IsValid() bool

IsValid is true if the key was not revoked, is not expired and used not more than it was supposed to

type SetupKeyType

type SetupKeyType string

SetupKeyType is the type of setup key

type SetupKeyUpdateOperation added in v0.9.2

type SetupKeyUpdateOperation struct {
	Type   SetupKeyUpdateOperationType
	Values []string
}

SetupKeyUpdateOperation operation object with type and values to be applied

type SetupKeyUpdateOperationType added in v0.9.2

type SetupKeyUpdateOperationType int

SetupKeyUpdateOperationType operation type

const (
	// UpdateSetupKeyName indicates a setup key name update operation
	UpdateSetupKeyName SetupKeyUpdateOperationType = iota
	// UpdateSetupKeyRevoked indicates a setup key revoked filed update operation
	UpdateSetupKeyRevoked
	// UpdateSetupKeyAutoGroups indicates a setup key auto-assign groups update operation
	UpdateSetupKeyAutoGroups
	// UpdateSetupKeyExpiresAt indicates a setup key expiration time update operation
	UpdateSetupKeyExpiresAt
)

func (SetupKeyUpdateOperationType) String added in v0.9.2

type SqlStore added in v0.27.8

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

SqlStore represents an account storage backed by a Sql DB persisted to disk

func NewPostgresqlStore added in v0.27.8

func NewPostgresqlStore(ctx context.Context, dsn string, metrics telemetry.AppMetrics) (*SqlStore, error)

NewPostgresqlStore creates a new Postgres store.

func NewPostgresqlStoreFromSqlStore added in v0.30.0

func NewPostgresqlStoreFromSqlStore(ctx context.Context, sqliteStore *SqlStore, dsn string, metrics telemetry.AppMetrics) (*SqlStore, error)

NewPostgresqlStoreFromSqlStore restores a store from SqlStore and stores Postgres DB.

func NewSqlStore added in v0.27.8

func NewSqlStore(ctx context.Context, db *gorm.DB, storeEngine StoreEngine, metrics telemetry.AppMetrics) (*SqlStore, error)

NewSqlStore creates a new SqlStore instance.

func NewSqliteStore added in v0.24.0

func NewSqliteStore(ctx context.Context, dataDir string, metrics telemetry.AppMetrics) (*SqlStore, error)

NewSqliteStore creates a new SQLite store.

func NewSqliteStoreFromFileStore added in v0.24.0

func NewSqliteStoreFromFileStore(ctx context.Context, fileStore *FileStore, dataDir string, metrics telemetry.AppMetrics) (*SqlStore, error)

NewSqliteStoreFromFileStore restores a store from FileStore and stores SQLite DB in the file located in datadir.

func (*SqlStore) AccountExists added in v0.30.0

func (s *SqlStore) AccountExists(ctx context.Context, lockStrength LockingStrength, id string) (bool, error)

AccountExists checks whether an account exists by the given ID.

func (*SqlStore) AcquireGlobalLock added in v0.27.8

func (s *SqlStore) AcquireGlobalLock(ctx context.Context) (unlock func())

AcquireGlobalLock acquires global lock across all the accounts and returns a function that releases the lock

func (*SqlStore) AcquireReadLockByUID added in v0.28.7

func (s *SqlStore) AcquireReadLockByUID(ctx context.Context, uniqueID string) (unlock func())

AcquireReadLockByUID acquires an ID lock for writing to a resource and returns a function that releases the lock

func (*SqlStore) AcquireWriteLockByUID added in v0.28.7

func (s *SqlStore) AcquireWriteLockByUID(ctx context.Context, uniqueID string) (unlock func())

AcquireWriteLockByUID acquires an ID lock for writing to a resource and returns a function that releases the lock

func (*SqlStore) AddPeerToAccount added in v0.29.3

func (s *SqlStore) AddPeerToAccount(ctx context.Context, peer *nbpeer.Peer) error

func (*SqlStore) AddPeerToAllGroup added in v0.29.3

func (s *SqlStore) AddPeerToAllGroup(ctx context.Context, accountID string, peerID string) error

func (*SqlStore) AddPeerToGroup added in v0.29.3

func (s *SqlStore) AddPeerToGroup(ctx context.Context, accountId string, peerId string, groupID string) error

func (*SqlStore) Close added in v0.27.8

func (s *SqlStore) Close(_ context.Context) error

Close closes the underlying DB connection

func (*SqlStore) DeleteAccount added in v0.27.8

func (s *SqlStore) DeleteAccount(ctx context.Context, account *Account) error

func (*SqlStore) DeleteHashedPAT2TokenIDIndex added in v0.27.8

func (s *SqlStore) DeleteHashedPAT2TokenIDIndex(hashedToken string) error

DeleteHashedPAT2TokenIDIndex is noop in SqlStore

func (*SqlStore) DeleteSetupKey added in v0.31.0

func (s *SqlStore) DeleteSetupKey(ctx context.Context, accountID, keyID string) error

func (*SqlStore) DeleteTokenID2UserIDIndex added in v0.27.8

func (s *SqlStore) DeleteTokenID2UserIDIndex(tokenID string) error

DeleteTokenID2UserIDIndex is noop in SqlStore

func (*SqlStore) ExecuteInTransaction added in v0.29.3

func (s *SqlStore) ExecuteInTransaction(ctx context.Context, operation func(store Store) error) error

func (*SqlStore) GetAccount added in v0.27.8

func (s *SqlStore) GetAccount(ctx context.Context, accountID string) (*Account, error)

func (*SqlStore) GetAccountByPeerID added in v0.27.8

func (s *SqlStore) GetAccountByPeerID(ctx context.Context, peerID string) (*Account, error)

func (*SqlStore) GetAccountByPeerPubKey added in v0.27.8

func (s *SqlStore) GetAccountByPeerPubKey(ctx context.Context, peerKey string) (*Account, error)

func (*SqlStore) GetAccountByPrivateDomain added in v0.27.8

func (s *SqlStore) GetAccountByPrivateDomain(ctx context.Context, domain string) (*Account, error)

func (*SqlStore) GetAccountBySetupKey added in v0.27.8

func (s *SqlStore) GetAccountBySetupKey(ctx context.Context, setupKey string) (*Account, error)

func (*SqlStore) GetAccountByUser added in v0.27.8

func (s *SqlStore) GetAccountByUser(ctx context.Context, userID string) (*Account, error)

func (*SqlStore) GetAccountDNSSettings added in v0.30.0

func (s *SqlStore) GetAccountDNSSettings(ctx context.Context, lockStrength LockingStrength, accountID string) (*DNSSettings, error)

func (*SqlStore) GetAccountDomainAndCategory added in v0.30.0

func (s *SqlStore) GetAccountDomainAndCategory(ctx context.Context, lockStrength LockingStrength, accountID string) (string, string, error)

GetAccountDomainAndCategory retrieves the Domain and DomainCategory fields for an account based on the given accountID.

func (*SqlStore) GetAccountGroups added in v0.28.8

func (s *SqlStore) GetAccountGroups(ctx context.Context, accountID string) ([]*nbgroup.Group, error)

func (*SqlStore) GetAccountIDByPeerPubKey added in v0.27.8

func (s *SqlStore) GetAccountIDByPeerPubKey(ctx context.Context, peerKey string) (string, error)

func (*SqlStore) GetAccountIDByPrivateDomain added in v0.30.0

func (s *SqlStore) GetAccountIDByPrivateDomain(ctx context.Context, lockStrength LockingStrength, domain string) (string, error)

func (*SqlStore) GetAccountIDBySetupKey added in v0.28.0

func (s *SqlStore) GetAccountIDBySetupKey(ctx context.Context, setupKey string) (string, error)

func (*SqlStore) GetAccountIDByUserID added in v0.28.0

func (s *SqlStore) GetAccountIDByUserID(userID string) (string, error)

func (*SqlStore) GetAccountNameServerGroups added in v0.30.0

func (s *SqlStore) GetAccountNameServerGroups(ctx context.Context, lockStrength LockingStrength, accountID string) ([]*nbdns.NameServerGroup, error)

GetAccountNameServerGroups retrieves name server groups for an account.

func (*SqlStore) GetAccountNetwork added in v0.29.3

func (s *SqlStore) GetAccountNetwork(ctx context.Context, lockStrength LockingStrength, accountID string) (*Network, error)

func (*SqlStore) GetAccountPolicies added in v0.30.0

func (s *SqlStore) GetAccountPolicies(ctx context.Context, lockStrength LockingStrength, accountID string) ([]*Policy, error)

GetAccountPolicies retrieves policies for an account.

func (*SqlStore) GetAccountPostureChecks added in v0.30.0

func (s *SqlStore) GetAccountPostureChecks(ctx context.Context, lockStrength LockingStrength, accountID string) ([]*posture.Checks, error)

GetAccountPostureChecks retrieves posture checks for an account.

func (*SqlStore) GetAccountRoutes added in v0.30.0

func (s *SqlStore) GetAccountRoutes(ctx context.Context, lockStrength LockingStrength, accountID string) ([]*route.Route, error)

GetAccountRoutes retrieves network routes for an account.

func (*SqlStore) GetAccountSettings added in v0.28.0

func (s *SqlStore) GetAccountSettings(ctx context.Context, lockStrength LockingStrength, accountID string) (*Settings, error)

func (*SqlStore) GetAccountSetupKeys added in v0.30.0

func (s *SqlStore) GetAccountSetupKeys(ctx context.Context, lockStrength LockingStrength, accountID string) ([]*SetupKey, error)

GetAccountSetupKeys retrieves setup keys for an account.

func (*SqlStore) GetAccountUsers added in v0.30.2

func (s *SqlStore) GetAccountUsers(ctx context.Context, accountID string) ([]*User, error)

func (*SqlStore) GetAllAccounts added in v0.27.8

func (s *SqlStore) GetAllAccounts(ctx context.Context) (all []*Account)

func (*SqlStore) GetDB added in v0.30.0

func (s *SqlStore) GetDB() *gorm.DB

func (*SqlStore) GetGroupByID added in v0.30.0

func (s *SqlStore) GetGroupByID(ctx context.Context, lockStrength LockingStrength, groupID, accountID string) (*nbgroup.Group, error)

GetGroupByID retrieves a group by ID and account ID.

func (*SqlStore) GetGroupByName added in v0.30.0

func (s *SqlStore) GetGroupByName(ctx context.Context, lockStrength LockingStrength, groupName, accountID string) (*nbgroup.Group, error)

GetGroupByName retrieves a group by name and account ID.

func (*SqlStore) GetInstallationID added in v0.27.8

func (s *SqlStore) GetInstallationID() string

func (*SqlStore) GetNameServerGroupByID added in v0.30.0

func (s *SqlStore) GetNameServerGroupByID(ctx context.Context, lockStrength LockingStrength, nsGroupID string, accountID string) (*nbdns.NameServerGroup, error)

GetNameServerGroupByID retrieves a name server group by its ID and account ID.

func (*SqlStore) GetPeerByPeerPubKey added in v0.28.0

func (s *SqlStore) GetPeerByPeerPubKey(ctx context.Context, lockStrength LockingStrength, peerKey string) (*nbpeer.Peer, error)

func (*SqlStore) GetPeerLabelsInAccount added in v0.29.3

func (s *SqlStore) GetPeerLabelsInAccount(ctx context.Context, lockStrength LockingStrength, accountID string) ([]string, error)

func (*SqlStore) GetPolicyByID added in v0.30.0

func (s *SqlStore) GetPolicyByID(ctx context.Context, lockStrength LockingStrength, policyID string, accountID string) (*Policy, error)

GetPolicyByID retrieves a policy by its ID and account ID.

func (*SqlStore) GetPostureCheckByChecksDefinition added in v0.28.0

func (s *SqlStore) GetPostureCheckByChecksDefinition(accountID string, checks *posture.ChecksDefinition) (*posture.Checks, error)

func (*SqlStore) GetPostureChecksByID added in v0.30.0

func (s *SqlStore) GetPostureChecksByID(ctx context.Context, lockStrength LockingStrength, postureCheckID string, accountID string) (*posture.Checks, error)

GetPostureChecksByID retrieves posture checks by their ID and account ID.

func (*SqlStore) GetRouteByID added in v0.30.0

func (s *SqlStore) GetRouteByID(ctx context.Context, lockStrength LockingStrength, routeID string, accountID string) (*route.Route, error)

GetRouteByID retrieves a route by its ID and account ID.

func (*SqlStore) GetSetupKeyByID added in v0.30.0

func (s *SqlStore) GetSetupKeyByID(ctx context.Context, lockStrength LockingStrength, setupKeyID string, accountID string) (*SetupKey, error)

GetSetupKeyByID retrieves a setup key by its ID and account ID.

func (*SqlStore) GetSetupKeyBySecret added in v0.29.3

func (s *SqlStore) GetSetupKeyBySecret(ctx context.Context, lockStrength LockingStrength, key string) (*SetupKey, error)

func (*SqlStore) GetStoreEngine added in v0.27.8

func (s *SqlStore) GetStoreEngine() StoreEngine

GetStoreEngine returns underlying store engine

func (*SqlStore) GetTakenIPs added in v0.29.3

func (s *SqlStore) GetTakenIPs(ctx context.Context, lockStrength LockingStrength, accountID string) ([]net.IP, error)

func (*SqlStore) GetTokenIDByHashedToken added in v0.27.8

func (s *SqlStore) GetTokenIDByHashedToken(ctx context.Context, hashedToken string) (string, error)

func (*SqlStore) GetUserByTokenID added in v0.27.8

func (s *SqlStore) GetUserByTokenID(ctx context.Context, tokenID string) (*User, error)

func (*SqlStore) GetUserByUserID added in v0.28.8

func (s *SqlStore) GetUserByUserID(ctx context.Context, lockStrength LockingStrength, userID string) (*User, error)

func (*SqlStore) GetUserPeers added in v0.30.0

func (s *SqlStore) GetUserPeers(ctx context.Context, lockStrength LockingStrength, accountID, userID string) ([]*nbpeer.Peer, error)

GetUserPeers retrieves peers for a user.

func (*SqlStore) IncrementNetworkSerial added in v0.29.3

func (s *SqlStore) IncrementNetworkSerial(ctx context.Context, accountId string) error

func (*SqlStore) IncrementSetupKeyUsage added in v0.29.3

func (s *SqlStore) IncrementSetupKeyUsage(ctx context.Context, setupKeyID string) error

func (*SqlStore) SaveAccount added in v0.27.8

func (s *SqlStore) SaveAccount(ctx context.Context, account *Account) error

func (*SqlStore) SaveGroup added in v0.30.0

func (s *SqlStore) SaveGroup(ctx context.Context, lockStrength LockingStrength, group *nbgroup.Group) error

SaveGroup saves a group to the store.

func (*SqlStore) SaveGroups added in v0.28.5

func (s *SqlStore) SaveGroups(ctx context.Context, lockStrength LockingStrength, groups []*nbgroup.Group) error

SaveGroups saves the given list of groups to the database.

func (*SqlStore) SaveInstallationID added in v0.27.8

func (s *SqlStore) SaveInstallationID(_ context.Context, ID string) error

func (*SqlStore) SavePeer added in v0.28.7

func (s *SqlStore) SavePeer(ctx context.Context, accountID string, peer *nbpeer.Peer) error

func (*SqlStore) SavePeerLocation added in v0.27.8

func (s *SqlStore) SavePeerLocation(accountID string, peerWithLocation *nbpeer.Peer) error

func (*SqlStore) SavePeerStatus added in v0.27.8

func (s *SqlStore) SavePeerStatus(accountID, peerID string, peerStatus nbpeer.PeerStatus) error

func (*SqlStore) SaveUser added in v0.30.0

func (s *SqlStore) SaveUser(ctx context.Context, lockStrength LockingStrength, user *User) error

SaveUser saves the given user to the database.

func (*SqlStore) SaveUserLastLogin added in v0.27.8

func (s *SqlStore) SaveUserLastLogin(ctx context.Context, accountID, userID string, lastLogin time.Time) error

SaveUserLastLogin stores the last login time for a user in DB.

func (*SqlStore) SaveUsers added in v0.28.5

func (s *SqlStore) SaveUsers(accountID string, users map[string]*User) error

SaveUsers saves the given list of users to the database. It updates existing users if a conflict occurs.

func (*SqlStore) UpdateAccountDomainAttributes added in v0.30.2

func (s *SqlStore) UpdateAccountDomainAttributes(ctx context.Context, accountID string, domain string, category string, isPrimaryDomain bool) error

type Store

type Store interface {
	GetAllAccounts(ctx context.Context) []*Account
	GetAccount(ctx context.Context, accountID string) (*Account, error)
	AccountExists(ctx context.Context, lockStrength LockingStrength, id string) (bool, error)
	GetAccountDomainAndCategory(ctx context.Context, lockStrength LockingStrength, accountID string) (string, string, error)
	GetAccountByUser(ctx context.Context, userID string) (*Account, error)
	GetAccountByPeerPubKey(ctx context.Context, peerKey string) (*Account, error)
	GetAccountIDByPeerPubKey(ctx context.Context, peerKey string) (string, error)
	GetAccountIDByUserID(userID string) (string, error)
	GetAccountIDBySetupKey(ctx context.Context, peerKey string) (string, error)
	GetAccountByPeerID(ctx context.Context, peerID string) (*Account, error)
	GetAccountBySetupKey(ctx context.Context, setupKey string) (*Account, error) // todo use key hash later
	GetAccountByPrivateDomain(ctx context.Context, domain string) (*Account, error)
	GetAccountIDByPrivateDomain(ctx context.Context, lockStrength LockingStrength, domain string) (string, error)
	GetAccountSettings(ctx context.Context, lockStrength LockingStrength, accountID string) (*Settings, error)
	GetAccountDNSSettings(ctx context.Context, lockStrength LockingStrength, accountID string) (*DNSSettings, error)
	SaveAccount(ctx context.Context, account *Account) error
	DeleteAccount(ctx context.Context, account *Account) error
	UpdateAccountDomainAttributes(ctx context.Context, accountID string, domain string, category string, isPrimaryDomain bool) error

	GetUserByTokenID(ctx context.Context, tokenID string) (*User, error)
	GetUserByUserID(ctx context.Context, lockStrength LockingStrength, userID string) (*User, error)
	GetAccountUsers(ctx context.Context, accountID string) ([]*User, error)
	SaveUsers(accountID string, users map[string]*User) error
	SaveUser(ctx context.Context, lockStrength LockingStrength, user *User) error
	SaveUserLastLogin(ctx context.Context, accountID, userID string, lastLogin time.Time) error
	GetTokenIDByHashedToken(ctx context.Context, secret string) (string, error)
	DeleteHashedPAT2TokenIDIndex(hashedToken string) error
	DeleteTokenID2UserIDIndex(tokenID string) error

	GetAccountGroups(ctx context.Context, accountID string) ([]*nbgroup.Group, error)
	GetGroupByID(ctx context.Context, lockStrength LockingStrength, groupID, accountID string) (*nbgroup.Group, error)
	GetGroupByName(ctx context.Context, lockStrength LockingStrength, groupName, accountID string) (*nbgroup.Group, error)
	SaveGroups(ctx context.Context, lockStrength LockingStrength, groups []*nbgroup.Group) error
	SaveGroup(ctx context.Context, lockStrength LockingStrength, group *nbgroup.Group) error

	GetAccountPolicies(ctx context.Context, lockStrength LockingStrength, accountID string) ([]*Policy, error)
	GetPolicyByID(ctx context.Context, lockStrength LockingStrength, policyID string, accountID string) (*Policy, error)

	GetPostureCheckByChecksDefinition(accountID string, checks *posture.ChecksDefinition) (*posture.Checks, error)
	GetAccountPostureChecks(ctx context.Context, lockStrength LockingStrength, accountID string) ([]*posture.Checks, error)
	GetPostureChecksByID(ctx context.Context, lockStrength LockingStrength, postureCheckID string, accountID string) (*posture.Checks, error)

	GetPeerLabelsInAccount(ctx context.Context, lockStrength LockingStrength, accountId string) ([]string, error)
	AddPeerToAllGroup(ctx context.Context, accountID string, peerID string) error
	AddPeerToGroup(ctx context.Context, accountId string, peerId string, groupID string) error
	AddPeerToAccount(ctx context.Context, peer *nbpeer.Peer) error
	GetPeerByPeerPubKey(ctx context.Context, lockStrength LockingStrength, peerKey string) (*nbpeer.Peer, error)
	GetUserPeers(ctx context.Context, lockStrength LockingStrength, accountID, userID string) ([]*nbpeer.Peer, error)
	SavePeer(ctx context.Context, accountID string, peer *nbpeer.Peer) error
	SavePeerStatus(accountID, peerID string, status nbpeer.PeerStatus) error
	SavePeerLocation(accountID string, peer *nbpeer.Peer) error

	GetSetupKeyBySecret(ctx context.Context, lockStrength LockingStrength, key string) (*SetupKey, error)
	IncrementSetupKeyUsage(ctx context.Context, setupKeyID string) error
	GetAccountSetupKeys(ctx context.Context, lockStrength LockingStrength, accountID string) ([]*SetupKey, error)
	GetSetupKeyByID(ctx context.Context, lockStrength LockingStrength, setupKeyID string, accountID string) (*SetupKey, error)

	GetAccountRoutes(ctx context.Context, lockStrength LockingStrength, accountID string) ([]*route.Route, error)
	GetRouteByID(ctx context.Context, lockStrength LockingStrength, routeID string, accountID string) (*route.Route, error)

	GetAccountNameServerGroups(ctx context.Context, lockStrength LockingStrength, accountID string) ([]*dns.NameServerGroup, error)
	GetNameServerGroupByID(ctx context.Context, lockStrength LockingStrength, nameServerGroupID string, accountID string) (*dns.NameServerGroup, error)

	GetTakenIPs(ctx context.Context, lockStrength LockingStrength, accountId string) ([]net.IP, error)
	IncrementNetworkSerial(ctx context.Context, accountId string) error
	GetAccountNetwork(ctx context.Context, lockStrength LockingStrength, accountId string) (*Network, error)

	GetInstallationID() string
	SaveInstallationID(ctx context.Context, ID string) error

	// AcquireWriteLockByUID should attempt to acquire a lock for write purposes and return a function that releases the lock
	AcquireWriteLockByUID(ctx context.Context, uniqueID string) func()
	// AcquireReadLockByUID should attempt to acquire lock for read purposes and return a function that releases the lock
	AcquireReadLockByUID(ctx context.Context, uniqueID string) func()
	// AcquireGlobalLock should attempt to acquire a global lock and return a function that releases the lock
	AcquireGlobalLock(ctx context.Context) func()

	// Close should close the store persisting all unsaved data.
	Close(ctx context.Context) error
	// GetStoreEngine should return StoreEngine of the current store implementation.
	// This is also a method of metrics.DataSource interface.
	GetStoreEngine() StoreEngine
	ExecuteInTransaction(ctx context.Context, f func(store Store) error) error
	DeleteSetupKey(ctx context.Context, accountID, keyID string) error
}

func NewStore

func NewStore(ctx context.Context, kind StoreEngine, dataDir string, metrics telemetry.AppMetrics) (Store, error)

NewStore creates a new store based on the provided engine type, data directory, and telemetry metrics

func NewTestStoreFromSQL added in v0.30.1

func NewTestStoreFromSQL(ctx context.Context, filename string, dataDir string) (Store, func(), error)

NewTestStoreFromSQL is only used in tests. It will create a test database base of the store engine set in env. Optionally it can load a SQL file to the database. If the filename is empty it will return an empty database

type StoreConfig added in v0.24.0

type StoreConfig struct {
	Engine StoreEngine
}

StoreConfig contains Store configuration

type StoreEngine added in v0.24.0

type StoreEngine string
const (
	FileStoreEngine     StoreEngine = "jsonfile"
	SqliteStoreEngine   StoreEngine = "sqlite"
	PostgresStoreEngine StoreEngine = "postgres"
)

type TURNConfig

type TURNConfig struct {
	TimeBasedCredentials bool
	CredentialsTTL       util.Duration
	Secret               string
	Turns                []*Host
}

TURNConfig is a config of the TURNCredentialsManager

type TimeBasedAuthSecretsManager

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

TimeBasedAuthSecretsManager generates credentials with TTL and using pre-shared secret known to TURN server

func NewTimeBasedAuthSecretsManager

func NewTimeBasedAuthSecretsManager(updateManager *PeersUpdateManager, turnCfg *TURNConfig, relayCfg *Relay) *TimeBasedAuthSecretsManager

func (*TimeBasedAuthSecretsManager) CancelRefresh

func (m *TimeBasedAuthSecretsManager) CancelRefresh(peerID string)

CancelRefresh cancels scheduled peer credentials refresh

func (*TimeBasedAuthSecretsManager) GenerateRelayToken added in v0.29.0

func (m *TimeBasedAuthSecretsManager) GenerateRelayToken() (*Token, error)

GenerateRelayToken generates new time-based secret credentials for relay

func (*TimeBasedAuthSecretsManager) GenerateTurnToken added in v0.29.0

func (m *TimeBasedAuthSecretsManager) GenerateTurnToken() (*Token, error)

GenerateTurnToken generates new time-based secret credentials for TURN

func (*TimeBasedAuthSecretsManager) SetupRefresh

func (m *TimeBasedAuthSecretsManager) SetupRefresh(ctx context.Context, peerID string)

SetupRefresh starts peer credentials refresh

type Token added in v0.29.0

type Token auth.Token

type UpdateMessage

type UpdateMessage struct {
	Update     *proto.SyncResponse
	NetworkMap *NetworkMap
}

type User

type User struct {
	Id string `gorm:"primaryKey"`
	// AccountID is a reference to Account that this object belongs
	AccountID     string `json:"-" gorm:"index"`
	Role          UserRole
	IsServiceUser bool
	// NonDeletable indicates whether the service user can be deleted
	NonDeletable bool
	// ServiceUserName is only set if IsServiceUser is true
	ServiceUserName string
	// AutoGroups is a list of Group IDs to auto-assign to peers registered by this user
	AutoGroups []string                        `gorm:"serializer:json"`
	PATs       map[string]*PersonalAccessToken `gorm:"-"`
	PATsG      []PersonalAccessToken           `json:"-" gorm:"foreignKey:UserID;references:id"`
	// Blocked indicates whether the user is blocked. Blocked users can't use the system.
	Blocked bool
	// LastLogin is the last time the user logged in to IdP
	LastLogin time.Time
	// CreatedAt records the time the user was created
	CreatedAt time.Time

	// Issued of the user
	Issued string `gorm:"default:api"`

	IntegrationReference integration_reference.IntegrationReference `gorm:"embedded;embeddedPrefix:integration_ref_"`
}

User represents a user of the system

func NewAdminUser

func NewAdminUser(id string) *User

NewAdminUser creates a new user with role UserRoleAdmin

func NewOwnerUser added in v0.24.4

func NewOwnerUser(id string) *User

NewOwnerUser creates a new user with role UserRoleOwner

func NewRegularUser

func NewRegularUser(id string) *User

NewRegularUser creates a new user with role UserRoleUser

func NewUser

func NewUser(id string, role UserRole, isServiceUser bool, nonDeletable bool, serviceUserName string, autoGroups []string, issued string) *User

NewUser creates a new user

func (*User) Copy

func (u *User) Copy() *User

Copy the user

func (*User) HasAdminPower added in v0.24.4

func (u *User) HasAdminPower() bool

HasAdminPower returns true if the user has admin or owner roles, false otherwise

func (*User) IsAdminOrServiceUser added in v0.30.0

func (u *User) IsAdminOrServiceUser() bool

IsAdminOrServiceUser checks if the user has admin power or is a service user.

func (*User) IsBlocked added in v0.20.0

func (u *User) IsBlocked() bool

IsBlocked returns true if the user is blocked, false otherwise

func (*User) LastDashboardLoginChanged added in v0.22.7

func (u *User) LastDashboardLoginChanged(LastLogin time.Time) bool

func (*User) ToUserInfo added in v0.20.0

func (u *User) ToUserInfo(userData *idp.UserData, settings *Settings) (*UserInfo, error)

ToUserInfo converts a User object to a UserInfo object.

type UserInfo

type UserInfo struct {
	ID                   string                                     `json:"id"`
	Email                string                                     `json:"email"`
	Name                 string                                     `json:"name"`
	Role                 string                                     `json:"role"`
	AutoGroups           []string                                   `json:"auto_groups"`
	Status               string                                     `json:"-"`
	IsServiceUser        bool                                       `json:"is_service_user"`
	IsBlocked            bool                                       `json:"is_blocked"`
	NonDeletable         bool                                       `json:"non_deletable"`
	LastLogin            time.Time                                  `json:"last_login"`
	Issued               string                                     `json:"issued"`
	IntegrationReference integration_reference.IntegrationReference `json:"-"`
	Permissions          UserPermissions                            `json:"permissions"`
}

type UserPermissions added in v0.26.4

type UserPermissions struct {
	DashboardView string `json:"dashboard_view"`
}

type UserRole

type UserRole string

UserRole is the role of a User

func StrRoleToUserRole added in v0.9.5

func StrRoleToUserRole(strRole string) UserRole

StrRoleToUserRole returns UserRole for a given strRole or UserRoleUnknown if the specified role is unknown

type UserStatus added in v0.9.8

type UserStatus string

UserStatus is the status of a User

Directories

Path Synopsis
api
Package api provides primitives to interact with the openapi HTTP API.
Package api provides primitives to interact with the openapi HTTP API.
Package metrics gather anonymous information about the usage of NetBird management
Package metrics gather anonymous information about the usage of NetBird management

Jump to

Keyboard shortcuts

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