types

package
v0.52.2 Latest Latest
Warning

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

Go to latest
Published: Jul 30, 2025 License: BSD-3-Clause Imports: 42 Imported by: 5

Documentation

Index

Constants

View Source
const (
	DefaultPeerLoginExpiration      = 24 * time.Hour
	DefaultPeerInactivityExpiration = 10 * time.Minute

	PublicCategory  = "public"
	PrivateCategory = "private"
	UnknownCategory = "unknown"
)
View Source
const (
	UDP   Protocol = "udp"
	DTLS  Protocol = "dtls"
	TCP   Protocol = "tcp"
	HTTP  Protocol = "http"
	HTTPS Protocol = "https"
	NONE  Provider = "none"
)
View Source
const (
	FirewallRuleDirectionIN  = 0
	FirewallRuleDirectionOUT = 1
)
View Source
const (
	GroupIssuedAPI         = "api"
	GroupIssuedJWT         = "jwt"
	GroupIssuedIntegration = "integration"
)
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"
	UserRoleAuditor      UserRole = "auditor"
	UserRoleNetworkAdmin UserRole = "network_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

View Source
var MgmtConfigPath string

Functions

func AddPeerLabelsToAccount

func AddPeerLabelsToAccount(ctx context.Context, account *Account, peerLabels LookupMap)

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 AllocateRandomPeerIP added in v0.50.0

func AllocateRandomPeerIP(ipNet net.IPNet) (net.IP, error)

func GetPeerHostLabel

func GetPeerHostLabel(name string, peerLabels LookupMap) (string, error)

func HiddenKey

func HiddenKey(key string, length int) string

HiddenKey returns the Key value hidden with "*" and a 5 character prefix. E.g., "831F6*******************************"

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]*Group                 `gorm:"-"`
	GroupsG                []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_"`
	Networks         []*networkTypes.Network          `gorm:"foreignKey:AccountID;references:id"`
	NetworkRouters   []*routerTypes.NetworkRouter     `gorm:"foreignKey:AccountID;references:id"`
	NetworkResources []*resourceTypes.NetworkResource `gorm:"foreignKey:AccountID;references:id"`
	Onboarding       AccountOnboarding                `gorm:"foreignKey:AccountID;references:id;constraint:OnDelete:CASCADE"`
}

Account represents a unique account of the system

func (*Account) AddAllGroup added in v0.37.1

func (a *Account) AddAllGroup(disableDefaultPolicy bool) error

AddAllGroup to account object if it doesn't exist

func (*Account) Copy

func (a *Account) Copy() *Account

func (*Account) DeletePeer

func (a *Account) DeletePeer(peerID string)

DeletePeer deletes peer from the account cleaning up all the references

func (*Account) DeleteResource

func (a *Account) DeleteResource(resourceID string)

func (*Account) FindGroupByName

func (a *Account) FindGroupByName(groupName string) (*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

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

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

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

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

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

func (*Account) GetExpiredPeers

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

GetExpiredPeers returns peers that have been expired

func (*Account) GetGroup

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

GetGroup returns a group by ID if exists, nil otherwise

func (*Account) GetGroupAll

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

func (*Account) GetInactivePeers

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

GetInactivePeers returns peers that have been expired by inactivity

func (*Account) GetMeta added in v0.42.0

func (a *Account) GetMeta() *AccountMeta

func (*Account) GetNetworkResourcesRoutesToSync

func (a *Account) GetNetworkResourcesRoutesToSync(ctx context.Context, peerID string, resourcePolicies map[string][]*Policy, routers map[string]map[string]*routerTypes.NetworkRouter) (bool, []*route.Route, map[string]struct{})

GetNetworkResourcesRoutesToSync returns network routes for syncing with a specific peer and its ACL peers.

func (*Account) GetNextInactivePeerExpiration

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

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

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

GetPeer looks up a Peer by ID

func (*Account) GetPeerConnectionResources

func (a *Account) GetPeerConnectionResources(ctx context.Context, peer *nbpeer.Peer, validatedPeersMap map[string]struct{}) ([]*nbpeer.Peer, []*FirewallRule)

GetPeerConnectionResources for a given peer

This function returns the list of peers and firewall rules that are applicable to a given peer.

func (*Account) GetPeerDNSLabels

func (a *Account) GetPeerDNSLabels() LookupMap

func (*Account) GetPeerGroups

func (a *Account) GetPeerGroups(peerID string) LookupMap

func (*Account) GetPeerGroupsList

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

GetPeerGroupsList return with the list of groups ID.

func (*Account) GetPeerNetworkMap

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

GetPeerNetworkMap returns the networkmap for the given peer ID.

func (*Account) GetPeerNetworkResourceFirewallRules

func (a *Account) GetPeerNetworkResourceFirewallRules(ctx context.Context, peer *nbpeer.Peer, validatedPeersMap map[string]struct{}, routes []*route.Route, resourcePolicies map[string][]*Policy) []*RouteFirewallRule

GetPeerNetworkResourceFirewallRules gets the network resources firewall rules associated with a routing peer ID for the account.

func (*Account) GetPeerRoutesFirewallRules

func (a *Account) GetPeerRoutesFirewallRules(ctx context.Context, peerID string, validatedPeersMap map[string]struct{}) []*RouteFirewallRule

GetPeerRoutesFirewallRules gets the routes firewall rules associated with a routing peer ID for the account.

func (*Account) GetPeers

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

GetPeers returns a list of all Account peers

func (*Account) GetPeersCustomZone

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

func (*Account) GetPeersWithExpiration

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

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) GetPoliciesAppliedInNetwork

func (a *Account) GetPoliciesAppliedInNetwork(networkID string) []string

func (*Account) GetPoliciesForNetworkResource

func (a *Account) GetPoliciesForNetworkResource(resourceId string) []*Policy

GetPoliciesForNetworkResource retrieves the list of policies that apply to a specific network resource. A policy is deemed applicable if its destination groups include any of the given network resource groups or if its destination resource explicitly matches the provided resource.

func (*Account) GetPostureChecks

func (a *Account) GetPostureChecks(postureChecksID string) *posture.Checks

func (*Account) GetResourcePoliciesMap

func (a *Account) GetResourcePoliciesMap() map[string][]*Policy

GetResourcePoliciesMap returns a map of networks resource IDs and their associated policies.

func (*Account) GetResourceRoutersMap

func (a *Account) GetResourceRoutersMap() map[string]map[string]*routerTypes.NetworkRouter

func (*Account) GetRoutesByPrefixOrDomains

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

GetRoutesByPrefixOrDomains return list of routes by account and route prefix

func (*Account) GetRoutesToSync

func (a *Account) GetRoutesToSync(ctx context.Context, peerID string, aclPeers []*nbpeer.Peer) []*route.Route

GetRoutesToSync returns the enabled routes for the peer ID and the routes from the ACL peers that have distribution groups associated with the peer ID. Please mind, that the returned route.Route objects will contain Peer.Key instead of Peer.ID.

func (*Account) GetTakenIPs

func (a *Account) GetTakenIPs() []net.IP

func (*Account) UpdatePeer

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

UpdatePeer saves new or replaces existing peer

func (*Account) UpdateSettings

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

UpdateSettings saves new account settings

func (*Account) UserGroupsAddToPeers

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

UserGroupsAddToPeers adds groups to all peers of user

func (*Account) UserGroupsRemoveFromPeers

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

UserGroupsRemoveFromPeers removes groups from all peers of user

type AccountDNSSettings

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

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

type AccountMeta added in v0.42.0

type AccountMeta struct {
	// AccountId is the unique identifier of the account
	AccountID      string `gorm:"column:id"`
	CreatedAt      time.Time
	CreatedBy      string
	Domain         string
	DomainCategory string
}

AccountMeta is a struct that contains a stripped down version of the Account object. It doesn't carry any peers, groups, policies, or routes, etc. Just some metadata (e.g. ID, created by, created at, etc).

type AccountNetwork

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

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

type AccountOnboarding added in v0.50.0

type AccountOnboarding struct {
	AccountID             string `gorm:"primaryKey"`
	OnboardingFlowPending bool
	SignupFormPending     bool
	CreatedAt             time.Time
	UpdatedAt             time.Time
}

func (AccountOnboarding) IsEqual added in v0.50.0

func (o AccountOnboarding) IsEqual(onboarding AccountOnboarding) bool

IsEqual compares two AccountOnboarding objects and returns true if they are equal

type AccountSettings

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

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

type Config added in v0.39.2

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

	// disable default all-to-all policy
	DisableDefaultPolicy bool
}

Config of the Management service

func (Config) GetAuthAudiences added in v0.39.2

func (c Config) GetAuthAudiences() []string

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

type DNSSettings

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

func (d DNSSettings) Copy() DNSSettings

Copy returns a copy of the DNS settings

type DeviceAuthorizationFlow added in v0.39.2

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 Engine added in v0.39.2

type Engine string
const (
	PostgresStoreEngine Engine = "postgres"
	FileStoreEngine     Engine = "jsonfile"
	SqliteStoreEngine   Engine = "sqlite"
	MysqlStoreEngine    Engine = "mysql"
)

type ExtraSettings added in v0.39.0

type ExtraSettings struct {
	// PeerApprovalEnabled enables or disables the need for peers bo be approved by an administrator
	PeerApprovalEnabled bool

	// IntegratedValidator is the string enum for the integrated validator type
	IntegratedValidator string
	// IntegratedValidatorGroups list of group IDs to be used with integrated approval configurations
	IntegratedValidatorGroups []string `gorm:"serializer:json"`

	FlowEnabled              bool `gorm:"-"`
	FlowPacketCounterEnabled bool `gorm:"-"`
	FlowENCollectionEnabled  bool `gorm:"-"`
	FlowDnsCollectionEnabled bool `gorm:"-"`
}

func (*ExtraSettings) Copy added in v0.39.0

func (e *ExtraSettings) Copy() *ExtraSettings

Copy copies the ExtraSettings struct

type FirewallRule

type FirewallRule struct {
	// PolicyID is the ID of the policy this rule is derived from
	PolicyID string

	// 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

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

FirewallRule is a rule of the firewall.

func (*FirewallRule) Equal added in v0.38.0

func (r *FirewallRule) Equal(other *FirewallRule) bool

Equal checks if two firewall rules are equal.

type ForwardingRule added in v0.38.0

type ForwardingRule struct {
	RuleProtocol      string
	DestinationPorts  RulePortRange
	TranslatedAddress net.IP
	TranslatedPorts   RulePortRange
}

func (*ForwardingRule) Equal added in v0.38.0

func (f *ForwardingRule) Equal(other *ForwardingRule) bool

func (*ForwardingRule) ToProto added in v0.38.0

func (f *ForwardingRule) ToProto() *proto.ForwardingRule

type Group

type Group struct {
	// ID of the group
	ID string `gorm:"primaryKey"`

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

	// Name visible in the UI
	Name string

	// Issued defines how this group was created (enum of "api", "integration" or "jwt")
	Issued string

	// Peers list of the group
	Peers []string `gorm:"serializer:json"`

	// Resources contains a list of resources in that group
	Resources []Resource `gorm:"serializer:json"`

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

Group of the peers for ACL

func (*Group) AddPeer

func (g *Group) AddPeer(peerID string) bool

AddPeer adds peerID to Peers if not present, returning true if added.

func (*Group) AddResource

func (g *Group) AddResource(resource Resource) bool

AddResource adds resource to Resources if not present, returning true if added.

func (*Group) Copy

func (g *Group) Copy() *Group

func (*Group) EventMeta

func (g *Group) EventMeta() map[string]any

EventMeta returns activity event meta related to the group

func (*Group) EventMetaResource

func (g *Group) EventMetaResource(resource *types.NetworkResource) map[string]any

func (*Group) HasPeers

func (g *Group) HasPeers() bool

HasPeers checks if the group has any peers.

func (*Group) HasResources

func (g *Group) HasResources() bool

HasResources checks if the group has any resources.

func (*Group) IsGroupAll

func (g *Group) IsGroupAll() bool

IsGroupAll checks if the group is a default "All" group.

func (*Group) RemovePeer

func (g *Group) RemovePeer(peerID string) bool

RemovePeer removes peerID from Peers if present, returning true if removed.

func (*Group) RemoveResource

func (g *Group) RemoveResource(resource Resource) bool

RemoveResource removes resource from Resources if present, returning true if removed.

type Host added in v0.39.2

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

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

type HttpServerConfig added in v0.39.2

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 LookupMap

type LookupMap map[string]struct{}

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

	Mu sync.Mutex `json:"-" gorm:"-"`
}

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
	ForwardingRules     []*ForwardingRule
}

func (*NetworkMap) Merge added in v0.38.0

func (nm *NetworkMap) Merge(other *NetworkMap)

type PKCEAuthorizationFlow added in v0.39.2

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.39.0

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

	// ExtraDNSLabels is a list of extra DNS labels that the peer wants to use
	ExtraDNSLabels []string
}

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

type PeerSync added in v0.39.0

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 Manager on Sync request.

type PersonalAccessToken

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

func (*PersonalAccessToken) GetExpirationDate added in v0.36.0

func (t *PersonalAccessToken) GetExpirationDate() time.Time

GetExpirationDate returns the expiration time of the token.

func (*PersonalAccessToken) GetLastUsed added in v0.36.0

func (t *PersonalAccessToken) GetLastUsed() time.Time

GetLastUsed returns the last time the token was used.

type PersonalAccessTokenGenerated

type PersonalAccessTokenGenerated struct {
	PlainToken string
	PersonalAccessToken
}

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

func CreateNewPAT

func CreateNewPAT(name string, expirationInDays int, targetID, 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

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 GetAllRoutePoliciesFromGroups

func GetAllRoutePoliciesFromGroups(account *Account, accessControlGroups []string) []*Policy

GetAllRoutePoliciesFromGroups retrieves route policies associated with the specified access control groups and returns a list of policies that have rules with destinations matching the specified groups.

func (*Policy) Copy

func (p *Policy) Copy() *Policy

Copy returns a copy of the policy.

func (*Policy) EventMeta

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

EventMeta returns activity event meta related to this policy

func (*Policy) RuleGroups

func (p *Policy) RuleGroups() []string

RuleGroups returns a list of all groups referenced in the policy's rules, including sources and destinations.

func (*Policy) SourceGroups

func (p *Policy) SourceGroups() []string

SourceGroups returns a slice of all unique source groups referenced in the policy's rules.

func (*Policy) UpgradeAndFix

func (p *Policy) UpgradeAndFix()

UpgradeAndFix different version of policies to latest version

type PolicyRule

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"`

	// DestinationResource policy destination resource that the rule is applied to
	DestinationResource Resource `gorm:"serializer:json"`

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

	// SourceResource policy source resource that the rule is applied to
	SourceResource Resource `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

func (pm *PolicyRule) Copy() *PolicyRule

Copy returns a copy of a policy rule

type PolicyRuleDirection

type PolicyRuleDirection string

PolicyRuleDirection direction of traffic

type PolicyRuleProtocolType

type PolicyRuleProtocolType string

PolicyRuleProtocolType type of traffic

type PolicyTrafficActionType

type PolicyTrafficActionType string

PolicyTrafficActionType action type for the firewall

type PolicyUpdateOperation

type PolicyUpdateOperation struct {
	Type   PolicyUpdateOperationType
	Values []string
}

PolicyUpdateOperation operation object with type and values to be applied

type PolicyUpdateOperationType

type PolicyUpdateOperationType int

PolicyUpdateOperationType operation type

type Protocol added in v0.39.2

type Protocol string

Protocol type

type Provider added in v0.39.2

type Provider string

Provider authorization flow type

type ProviderConfig added in v0.39.2

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
	// DisablePromptLogin makes the PKCE flow to not prompt the user for login
	DisablePromptLogin bool
	// LoginFlag is used to configure the PKCE flow login behavior
	LoginFlag common.LoginFlag
}

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

type Relay added in v0.39.2

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

Relay configuration type

type Resource

type Resource struct {
	ID   string
	Type string
}

func (*Resource) FromAPIRequest

func (r *Resource) FromAPIRequest(req *api.Resource)

func (*Resource) ToAPIResponse

func (r *Resource) ToAPIResponse() *api.Resource

type ReverseProxy added in v0.39.2

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

type RouteFirewallRule struct {
	// PolicyID is the ID of the policy this rule is derived from
	PolicyID string

	// RouteID is the ID of the route this rule belongs to.
	RouteID route.ID

	// 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

	// Domains list of network domains for the routed traffic
	Domains domain.List

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

RouteFirewallRule a firewall rule applicable for a routed network.

func (*RouteFirewallRule) Equal added in v0.38.0

func (r *RouteFirewallRule) Equal(other *RouteFirewallRule) bool

type RulePortRange

type RulePortRange struct {
	Start uint16
	End   uint16
}

RulePortRange represents a range of ports for a firewall rule.

func (*RulePortRange) Equal added in v0.38.0

func (r *RulePortRange) Equal(other *RulePortRange) bool

func (*RulePortRange) ToProto added in v0.38.0

func (r *RulePortRange) ToProto() *proto.PortInfo

type Settings

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"`

	// RoutingPeerDNSResolutionEnabled enabled the DNS resolution on the routing peers
	RoutingPeerDNSResolutionEnabled bool

	// DNSDomain is the custom domain for that account
	DNSDomain string

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

	// LazyConnectionEnabled indicates if the experimental feature is enabled or disabled
	LazyConnectionEnabled bool `gorm:"default:false"`
}

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

func (*Settings) Copy

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
	// AllowExtraDNSLabels indicates if the key allows extra DNS labels
	AllowExtraDNSLabels 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, allowExtraDNSLabels 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

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

EventMeta returns activity event meta related to the setup key

func (*SetupKey) GetExpiresAt added in v0.36.0

func (key *SetupKey) GetExpiresAt() time.Time

GetExpiresAt returns the expiration time of the setup key.

func (*SetupKey) GetLastUsed added in v0.36.0

func (key *SetupKey) GetLastUsed() time.Time

GetLastUsed returns the last used time of 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 StoreConfig added in v0.39.2

type StoreConfig struct {
	Engine Engine
}

StoreConfig contains Store configuration

type TURNConfig added in v0.39.2

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

TURNConfig is a config of the TURNCredentialsManager

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;constraint:OnDelete:CASCADE;"`
	// 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

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) GetLastLogin added in v0.36.0

func (u *User) GetLastLogin() time.Time

GetLastLogin returns the last login time of the user.

func (*User) HasAdminPower

func (u *User) HasAdminPower() bool

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

func (*User) IsAdminOrServiceUser

func (u *User) IsAdminOrServiceUser() bool

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

func (*User) IsBlocked

func (u *User) IsBlocked() bool

IsBlocked returns true if the user is blocked, false otherwise

func (*User) IsRegularUser

func (u *User) IsRegularUser() bool

IsRegularUser checks if the user is a regular user.

func (*User) IsRestrictable added in v0.43.2

func (u *User) IsRestrictable() bool

IsRestrictable checks whether a user is in a restrictable role.

func (*User) LastDashboardLoginChanged

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

func (*User) ToUserInfo

func (u *User) ToUserInfo(userData *idp.UserData) (*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:"-"`
}

type UserRole

type UserRole string

UserRole is the role of a User

func StrRoleToUserRole

func StrRoleToUserRole(strRole string) UserRole

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

type UserStatus

type UserStatus string

UserStatus is the status of a User

Jump to

Keyboard shortcuts

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