Documentation
¶
Overview ¶
package for logicing client and server code
Index ¶
- Constants
- Variables
- func AddEgressInfoToPeerByAccess(node, targetNode *models.Node, eli []schema.Egress, acls []models.Acl, ...)
- func AddHook(ifaceToAdd interface{})
- func AddSSOStateCleanupHook()
- func AddStaticNodestoList(ctx context.Context, nodes []models.Node) []models.Node
- func AddStatusToNodes(ctx context.Context, nodes []models.Node, statusCall bool) (nodesWithStatus []models.Node)
- func AllDomainAnsFromEgress(e schema.Egress) []string
- func AllocateUniquePoolFromFallback(pool *net.IPNet, newPrefixLen int, allocated map[string]struct{}, seed string) string
- func AllocateUniqueVNATPool(ctx context.Context, network *schema.Network) error
- func AppendEgressPolicyRange(e schema.Egress, rangeStr string, v4, v6 *[]net.IPNet)
- func ApplyConfiguredDomainsToEgress(e *schema.Egress, domains []string)
- func ApplyEgressPresetToEgressReq(req *models.EgressReq) error
- func ApplyExtClientInternetEgressSelection(ctx context.Context, client *models.ExtClient, gatewayNodeID string, ...) error
- func AssignNodeExitNode(ctx context.Context, network, nodeID, egressID string, useTcpUplink bool) (*models.DeviceExitNode, error)
- func AssignVirtualNATDefaults(network *schema.Network, vpnCIDR string)
- func AssociateNodeToHost(n *models.Node, h *schema.Host) error
- func AutoUpdateEnabled(ctx context.Context) bool
- func CancelDeviceNetworkJoin(ctx context.Context, user *schema.User, host *schema.Host, networkID string) error
- func CheckEndpoint(endpoint string) bool
- func CheckHostPorts(ctx context.Context, h *schema.Host) (changed bool)
- func CheckIfFileExists(filePath string) bool
- func CheckTagGroupPolicy(srcMap, dstMap map[string]struct{}, node, peer models.Node, ...) bool
- func CheckZombies(ctx context.Context, _node *schema.Node)
- func CleanExpiredSSOStates() error
- func CleanVersion(raw string) string
- func CleanupOtherExtclients(ctx context.Context, extclient *models.ExtClient) error
- func ClearEgressDomainAns(e *schema.Egress)
- func ClearExitNodeForDisconnect(node *models.Node) (bool, error)
- func ClearNodesSelectedInternetEgress(ctx context.Context, egressID, network string)
- func CompareIfaceSlices(a, b []schema.Iface) bool
- func CompareMaps[K comparable, V any](a, b map[K]V) bool
- func ConfiguredDomainsForEgress(e schema.Egress) []string
- func ContainsCIDR(net1, net2 string) bool
- func ContinueIfUserMatch(next http.Handler) http.HandlerFunc
- func ContinueIfUserMatchOrAdmin(next http.Handler) http.HandlerFunc
- func ConvAclTagToValueMap(acltags []models.AclPolicyTag) map[string]struct{}
- func ConvertModelsNodeToSchemaNode(node *models.Node) *schema.Node
- func ConvertSchemaNodeToApiNode(_node *schema.Node) *models.ApiNode
- func ConvertSchemaNodeToModelsNode(_node *schema.Node) *models.Node
- func ConvertSchemaNodeToModelsNodeWithContext(ctx context.Context, _node *schema.Node) *models.Node
- func CreateDNS(ctx context.Context, entry models.DNSEntry) (models.DNSEntry, error)
- func CreateDefaultAclNetworkPolicies(ctx context.Context, netID schema.NetworkID)
- func CreateDefaultNetworkEnrollmentKey(ctx context.Context, networkName string) (*schema.EnrollmentKey, error)
- func CreateEgressGateway(gateway models.EgressGatewayRequest) (models.Node, error)
- func CreateEnrollmentKey(ctx context.Context, uses int, expiration time.Time, networks, tags []string, ...) (*schema.EnrollmentKey, error)
- func CreateFallbackNameserver(network *schema.Network) error
- func CreateHost(ctx context.Context, h *schema.Host) error
- func CreateInternetEgressForNode(ctx context.Context, node *models.Node, name, createdBy string) (*schema.Egress, error)
- func CreateJWT(uuid string, macAddress string, network string) (response string, err error)
- func CreateNetwork(ctx context.Context, _network *schema.Network) error
- func CreatePreAuthToken(ctx context.Context, username string) (string, error)
- func CreateUserAccessJwtToken(ctx context.Context, username string, d time.Time, tokenID string) (response string, err error)
- func CreateUserJWT(ctx context.Context, username string, appName string) (response string, err error)
- func DeTokenize(ctx context.Context, b64Token string) (*schema.EnrollmentKey, error)
- func DefaultCleanupDeviceHostForOwnershipTransfer(ctx context.Context, host *schema.Host) error
- func DeleteAcl(ctx context.Context, a models.Acl) error
- func DeleteDNS(ctx context.Context, domain string, network string) error
- func DeleteEgressGateway(network, nodeid string) (models.Node, error)
- func DeleteEnrollmentKey(ctx context.Context, value string, force bool) error
- func DeleteExpiredNodes(ctx context.Context)
- func DeleteExtClient(ctx context.Context, network string, clientid string, isUpdate bool) error
- func DeleteExtClientAndCleanup(ctx context.Context, extClient models.ExtClient) error
- func DeleteGatewayExtClients(ctx context.Context, gatewayID string, networkName string) error
- func DeleteIngressGateway(ctx context.Context, nodeid string) (models.Node, []models.ExtClient, error)
- func DeleteInternetEgressesForRoutingNode(ctx context.Context, network, nodeID string)
- func DeleteNetwork(ctx context.Context, network string, force bool, done chan struct{}) error
- func DeleteNetworkDNS(ctx context.Context, network string) error
- func DeleteNetworkPolicies(ctx context.Context, netId schema.NetworkID)
- func DeleteNode(ctx context.Context, node *models.Node, purge bool) error
- func DeleteNodeByID(ctx context.Context, node *models.Node) error
- func DeleteOrgUser(ctx context.Context, user *schema.User, forceDeleteConfigs bool, ...) error
- func DeleteRelay(network, nodeid string) ([]models.Node, models.Node, error)
- func DeleteTenantUser(ctx context.Context, user *schema.User, forceDeleteConfigs bool, ...) error
- func DetachExitRoutingNode(ctx context.Context, node *models.Node) []models.Node
- func DisassociateAllNodesFromHost(ctx context.Context, hostIDStr string) error
- func DisassociateNodeFromHost(ctx context.Context, n *models.Node, h *schema.Host) error
- func DisplaceAutoRelayedNodes(nodeID string) []models.Node
- func DoesHostExistInTheNetworkAlready(h *schema.Host, network *schema.Network) bool
- func DoesNodeHaveAccessToEgress(node *models.Node, e *schema.Egress, acls []models.Acl) bool
- func DoesUserHaveAccessToEgress(user *schema.User, e *schema.Egress, acls []models.Acl) bool
- func DomainAnsForDomain(e schema.Egress, domain string) []string
- func DomainAnsMapFromEgress(e schema.Egress) map[string][]string
- func EgressDNs(ctx context.Context, network string) (entries []models.DNSEntry)
- func EgressDomainsEqual(a, b []string) bool
- func EnsureHostOwner(host *schema.Host, username string)
- func EnterpriseCheck(ctx context.Context, wg *sync.WaitGroup)
- func ErrExitClientBlocksAutoRelayRole(node *models.Node) error
- func ErrExitNodeBlocksAutoRelay(node *models.Node) error
- func ErrExitNodeBlocksGatewayOps(node *models.Node) error
- func ExitClientOverlayIPs(peer *models.Node, excludeID string) []net.IPNet
- func ExitClientOverlayIPsFromInetClients(peer *models.Node, excludeID string) []net.IPNet
- func ExpandEgressRouteRanges(e schema.Egress, includeIPv6 bool) []string
- func ExtClientUsesInternetEgress(client models.ExtClient, _ models.Node) bool
- func FailOpenAndDetachExitRoutingNode(ctx context.Context, node *models.Node)
- func FetchOAuthSecret(ctx context.Context) (string, error)
- func FileExists(f string) bool
- func FilterOutIPs(ips []string, filters map[string]bool) []string
- func FindInternetEgressByRoutingNode(ctx context.Context, network, nodeID string) (*schema.Egress, error)
- func FirstInternetEgressRoutingNodeID(e schema.Egress) string
- func FlattenDomainAnsMap(m map[string][]string) []string
- func FlushNodeCheckins()
- func FormatError(err error, errType ApiErrorType) models.ErrorResponse
- func GenerateNodeName(ctx context.Context, network string) (string, error)
- func GenerateOTPAuthURLSignature(url string) string
- func GetAcl(ctx context.Context, aID string) (models.Acl, error)
- func GetAclRuleForInetGw(targetnode models.Node) (rules map[string]models.AclRule)
- func GetAclRulesForNode(ctx context.Context, targetnodeI *models.Node) (rules map[string]models.AclRule)
- func GetAllDNS(ctx context.Context) ([]models.DNSEntry, error)
- func GetAllEnrollmentKeys(ctx context.Context) ([]schema.EnrollmentKey, error)
- func GetAllExtClients(ctx context.Context) ([]models.ExtClient, error)
- func GetAllExtClientsWithStatus(ctx context.Context, status schema.NodeStatus) ([]models.ExtClient, error)
- func GetAllHostsAPI(hosts []schema.Host) []models.ApiHost
- func GetAllHostsWithStatus(ctx context.Context, status schema.NodeStatus) ([]schema.Host, error)
- func GetAllNodes(ctx context.Context) ([]models.Node, error)
- func GetAllNodesAPI(nodes []models.Node) []models.ApiNode
- func GetAllNodesAPIWithLocation(nodes []models.Node) []models.ApiNode
- func GetAllRsrcIDForRsrc(rsrc schema.RsrcType) schema.RsrcID
- func GetAllowedEmailDomains(ctx context.Context) string
- func GetAllowedIPs(ctx context.Context, node, peer *models.Node, metrics *models.Metrics) []net.IPNet
- func GetAllowedIpForInetNodeClient(node, peer *models.Node) []net.IPNet
- func GetAllowedIpsForRelayed(ctx context.Context, relayed, relay *models.Node) (allowedIPs []net.IPNet)
- func GetAuditLogsRetentionPeriodInDays(ctx context.Context) int
- func GetAuthProviderInfo(settings models.ServerSettings) (pi []string)
- func GetAzureTenant(ctx context.Context) string
- func GetCachedHostPeerUpdate(ctx context.Context, hostID string) (models.HostPeerUpdate, bool)
- func GetClientIP(r *http.Request) string
- func GetCurrentServerUsage(ctx context.Context) (limits models.Usage)
- func GetCustomDNS(ctx context.Context, network string) ([]models.DNSEntry, error)
- func GetDNS(ctx context.Context, network string) ([]models.DNSEntry, error)
- func GetDNSEntryNum(ctx context.Context, domain string, network string) (int, error)
- func GetDefaultDomain(ctx context.Context) string
- func GetDefaultEnrollmentKeyForNetwork(ctx context.Context, network string) (*schema.EnrollmentKey, error)
- func GetDefaultHosts(ctx context.Context) []schema.Host
- func GetDefaultPolicy(ctx context.Context, netID schema.NetworkID, ruleType models.AclPolicyType) (models.Acl, error)
- func GetDefaultTenantSettings() models.ServerSettings
- func GetDeviceNetworks(ctx context.Context, user *schema.User, host *schema.Host) ([]models.DeviceNetwork, error)
- func GetDeviceSelectedExitNode(ctx context.Context, user *schema.User, host *schema.Host, networkID string) (*models.DeviceExitNode, error)
- func GetEgressDefaultAllowAllFwRule(node models.Node) (models.AclRule, bool)
- func GetEgressDomainNSForNode(ctx context.Context, node *models.Node) (returnNsLi []models.Nameserver)
- func GetEgressDomainsByAccessForUser(ctx context.Context, user *schema.User, network schema.NetworkID) (domains []string)
- func GetEgressIPs(peer *models.Node) []net.IPNet
- func GetEgressPresetByID(id string) (models.EgressPresetApp, bool)
- func GetEgressRanges(ctx context.Context, netID schema.NetworkID) (map[string][]string, map[string]struct{}, error)
- func GetEgressRangesOnNetwork(ctx context.Context, client *models.ExtClient) ([]string, error)
- func GetEgressRulesForNode(ctx context.Context, targetnode models.Node) (rules map[string]models.AclRule)
- func GetEmaiSenderPassword(ctx context.Context) string
- func GetEnrollmentKey(ctx context.Context, value string) (*schema.EnrollmentKey, error)
- func GetExtClient(ctx context.Context, clientid string, network string) (models.ExtClient, error)
- func GetExtClientByName(ctx context.Context, ID string) (models.ExtClient, error)
- func GetExtClientsByID(ctx context.Context, nodeid, network string) ([]models.ExtClient, error)
- func GetExtPeers(ctx context.Context, node, peer *models.Node, ...) ([]wgtypes.PeerConfig, []models.IDandAddr, []models.EgressNetworkRoutes, error)
- func GetExtclientAllowedIPs(ctx context.Context, client models.ExtClient) (allowedIPs []string)
- func GetExtclientDNS(ctx context.Context) []models.DNSEntry
- func GetFwRulesOnIngressGateway(ctx context.Context, node models.Node) (rules []models.FwRule)
- func GetGwDNS(node *models.Node) string
- func GetHostNetworks(ctx context.Context, hostID string) []string
- func GetHostNodes(host *schema.Host) []models.Node
- func GetHostPeerInfo(ctx context.Context, host *schema.Host) (models.HostPeerInfo, error)
- func GetIDPSyncInterval(ctx context.Context) time.Duration
- func GetIngressGwUsers(node models.Node) (models.IngressGwUsers, error)
- func GetJwtSecretValue() (string, error)
- func GetJwtValidityDuration(ctx context.Context) time.Duration
- func GetJwtValidityDurationForClients(ctx context.Context) time.Duration
- func GetLoginMethodsForUser(ctx context.Context, username string) ([]models.LoginOption, error)
- func GetManageDNS(ctx context.Context) bool
- func GetMetricInterval(ctx context.Context) string
- func GetMetricIntervalInMinutes(ctx context.Context) time.Duration
- func GetMetricsPort(ctx context.Context) int
- func GetNetworkExtClients(ctx context.Context, network string) ([]models.ExtClient, error)
- func GetNetworkNetworkCIDR4(network *schema.Network) *net.IPNet
- func GetNetworkNetworkCIDR6(network *schema.Network) *net.IPNet
- func GetNetworkNodes(ctx context.Context, network string) ([]models.Node, error)
- func GetNetworkNodesMemory(allNodes []models.Node, network string) []models.Node
- func GetNetworkNonServerNodeCount(ctx context.Context, networkName string) (int, error)
- func GetNodeByHostRef(ctx context.Context, hostid, network string) (node models.Node, err error)
- func GetNodeByID(nodeID string) (models.Node, error)
- func GetNodeCheckInStatus(node *schema.Node) schema.NodeStatus
- func GetNodeDNS(ctx context.Context, network string) ([]models.DNSEntry, error)
- func GetNodeEgressInfo(targetNode *models.Node, eli []schema.Egress, acls []models.Acl)
- func GetNodeExitNode(ctx context.Context, network, nodeID string) (*models.DeviceExitNode, error)
- func GetNodesByIDs(ids []string) (map[string]models.Node, error)
- func GetNodesStatusAPI(nodes []models.Node) map[string]models.ApiNodeStatus
- func GetOnboardingStatus(ctx context.Context, username string) (models.OnboardingStatus, error)
- func GetOrgSettings(ctx context.Context) schema.OrganizationSettingsData
- func GetPeerListenPort(host *schema.Host) int
- func GetPeerUpdateForHost(ctx context.Context, network string, host *schema.Host, allNodes []models.Node, ...) (hostPeerUpdate models.HostPeerUpdate, err error)
- func GetRacRestrictToSingleNetwork(ctx context.Context) bool
- func GetRecordKey(id string, network string) (string, error)
- func GetRunningHooks() []string
- func GetSelectedInternetEgress(node *models.Node) (*schema.Egress, error)
- func GetSenderEmail(ctx context.Context) string
- func GetSenderUser(ctx context.Context) string
- func GetServerConfig(ctx context.Context) config.ServerConfig
- func GetServerInfo(ctx context.Context) models.ServerConfig
- func GetServerSettings(ctx context.Context) (s models.ServerSettings)
- func GetServerSettingsFromEnv() (s models.ServerSettings)
- func GetSmtpHost(ctx context.Context) string
- func GetSmtpPort(ctx context.Context) int
- func GetState(state string) (*models.SsoState, error)
- func GetStaticNodeIps(ctx context.Context, node models.Node) (ips []net.IP)
- func GetStaticNodesByNetwork(ctx context.Context, network schema.NetworkID, onlyWg bool) (staticNode []models.Node)
- func GetStunServers(ctx context.Context) string
- func GetSuperAdmin(ctx context.Context) (models.ReturnUser, error)
- func GetTenantNetworkHookID(ctx context.Context) string
- func GetUserInvite(ctx context.Context, email string) (*schema.UserInvite, error)
- func GetUserMap() (map[string]schema.User, error)
- func GetUserNameFromToken(ctx context.Context, authtoken string) (username string, err error)
- func GetUserSettings(username string) models.UserSettings
- func GetVerbosity(ctx context.Context) int32
- func HasEgressDomainAns(e schema.Egress) bool
- func HostExists(h *schema.Host) bool
- func IfaceDelta(currentNode *models.Node, newNode *models.Node) bool
- func InferEgressType(req *models.EgressReq) schema.EgressType
- func InitNetworkHooks(ctx context.Context)
- func InsertAcl(ctx context.Context, a models.Acl) error
- func InternetEgressRanges(includeIPv6 bool) []string
- func InternetExitRoutingNodeID(node *models.Node) string
- func InvalidateHostPeerCaches(ctx context.Context)
- func InvalidateServerSettingsCache(ctx context.Context)
- func IsAWSEgressPreset(presetID string) bool
- func IsAclExists(ctx context.Context, aclID string) bool
- func IsAddressInCIDR(address net.IP, cidr string) bool
- func IsBase64(s string) bool
- func IsBasicAuthEnabled(ctx context.Context) bool
- func IsDNSEntryValid(d string) bool
- func IsDomainBasedEgress(e schema.Egress) bool
- func IsEgressAppEgress(e schema.Egress) bool
- func IsEgressDomainPattern(domain string) bool
- func IsEgressInternetGateway(e schema.Egress) bool
- func IsEgressReqInternetGateway(req *models.EgressReq) bool
- func IsEgressRoutingPolicyAllowedForNodes(policy models.Acl, node, peer models.Node) bool
- func IsEndpointDetectionEnabled(ctx context.Context) bool
- func IsFQDN(domain string) bool
- func IsIDPUser(ctx context.Context, user *schema.User) bool
- func IsInternetGw(node models.Node) bool
- func IsMFAEnforced(ctx context.Context) bool
- func IsNetworkCIDRUnique(ctx context.Context, cidr4 *net.IPNet, cidr6 *net.IPNet) bool
- func IsNetworkNameUnique(ctx context.Context, network *schema.Network) (bool, error)
- func IsNodeAllowedToCommunicate(ctx context.Context, node, peer models.Node, checkDefaultPolicy bool) (bool, []models.Acl)
- func IsNodeAllowedToCommunicateWithAllRsrcs(ctx context.Context, node models.Node) bool
- func IsOauthUser(ctx context.Context, user *schema.User) error
- func IsPendingUser(ctx context.Context, username string) bool
- func IsSlicesEqual(a, b []string) bool
- func IsStateValid(state string) (string, bool)
- func IsStunEnabled(ctx context.Context) bool
- func IsSyncEnabled(ctx context.Context) bool
- func IsUserAllowedAccessToExtClient(username string, client models.ExtClient) bool
- func IsValidMatchDomain(s string) bool
- func IsValidVersion(raw string) bool
- func IsVersionCompatible(ver string) bool
- func JoinDeviceNetwork(ctx context.Context, user *schema.User, host *schema.Host, networkID string) (models.DeviceJoinResult, error)
- func LeaveDeviceNetwork(ctx context.Context, user *schema.User, host *schema.Host, networkID string) error
- func ListAcls(ctx context.Context) (acls []models.Acl)
- func ListAclsByNetwork(ctx context.Context, netID schema.NetworkID) ([]models.Acl, error)
- func ListAllByRoutingNodeWithDomain(egs []schema.Egress, nodeID string) (egWithDomain []models.EgressDomain)
- func ListDeviceExitNodes(ctx context.Context, user *schema.User, host *schema.Host, networkID string) ([]models.DeviceExitNode, error)
- func ListDevicePolicies(ctx context.Context, netID schema.NetworkID) []models.Acl
- func ListEgressAcls(ctx context.Context, egressID string) ([]models.Acl, error)
- func ListEgressPresets() []models.EgressPresetApp
- func ListExitClientsForRoutingNode(ctx context.Context, network, routingNodeID string) []models.Node
- func ListNodeExitNodes(ctx context.Context, network, nodeID string) ([]models.DeviceExitNode, error)
- func ListNodesBySelectedInternetEgress(ctx context.Context, network, egressID string) []models.Node
- func ListUserPolicies(ctx context.Context, netID schema.NetworkID) []models.Acl
- func ManageZombies(ctx context.Context)
- func MarkStaleNodesOffline(ctx context.Context)
- func Mask() string
- func MigrateAclPolicies(ctx context.Context)
- func ModelsEnrollmentKeyFromSchema(key schema.EnrollmentKey) models.EnrollmentKey
- func NetworkExists(ctx context.Context, name string) (bool, error)
- func NodeIsInternetEgressRouter(ctx context.Context, nodeID, network string) bool
- func NormalizeAndValidateAclEgressIPs(acl *models.Acl) error
- func NormalizeCIDR(address string) (string, error)
- func NormalizeEgressReqDomains(domains []string) ([]string, error)
- func NormalizeEgressType(e *schema.Egress)
- func NormalizeIPOrCIDR(value string) (string, error)
- func NormalizeOSName(raw string) string
- func NotifyMetricExportIntervalChanged(ctx context.Context)
- func NthSubnet(pool *net.IPNet, newPrefixLen int, n int) *net.IPNet
- func OSFamily(osName string) string
- func PopulateAclPolicyTagNames(ctx context.Context, acls []models.Acl)
- func PreAuthCheck(next http.Handler) http.HandlerFunc
- func PresetYieldsAWSIPRanges(p models.EgressPresetApp) bool
- func PruneStaleRelayedClients(node *models.Node) bool
- func RandomString(length int) string
- func RebindInternetEgressClients(ctx context.Context, e schema.Egress)
- func RefreshHostPeerInfoCache(ctx context.Context) ([]schema.Host, []models.Node)
- func RegenerateEnrollmentKeyToken(ctx context.Context, keyValue string) (*schema.EnrollmentKey, error)
- func RegisterDevice(ctx context.Context, user *schema.User, newHost *schema.Host) (models.RegisterResponse, error)
- func RelayUpdates(currentNode, newNode *models.Node) bool
- func RelayedAllowedIPs(ctx context.Context, peer, node *models.Node) []net.IPNet
- func RemoveAllFromSlice[T comparable](s []T, val T) []T
- func RemoveHost(ctx context.Context, h *schema.Host, forceDelete bool) error
- func RemoveNodeFromAclPolicy(ctx context.Context, node models.Node)
- func RemoveNodeFromAllGatewayRelays(ctx context.Context, networkName, nodeID string)
- func RemoveNodeFromEgress(node models.Node)
- func RemoveNodeFromEnrollmentKeys(node *models.Node)
- func RemoveStringSlice(slice []string, i int) []string
- func RemoveTagFromEnrollmentKeys(deletedTagID models.TagID)
- func RequiresProEgressType(e schema.Egress) bool
- func ResetHook(hookID string)
- func ResolveAWSEgressPresetCIDRs(client *http.Client, p models.EgressPresetApp) ([]string, error)
- func ResolveInheritedAuth(ctx context.Context, user *schema.User) error
- func ResolveInternetExitRoutingNode(node *models.Node)
- func RestartHook(hookID string, newInterval time.Duration)
- func RetrievePrivateTrafficKey() ([]byte, error)
- func RetrievePublicTrafficKey() ([]byte, error)
- func ReturnAcceptedResponse(response http.ResponseWriter, request *http.Request, message string)
- func ReturnErrorResponse(response http.ResponseWriter, request *http.Request, ...)
- func ReturnErrorResponseWithJson(response http.ResponseWriter, request *http.Request, msg interface{}, ...)
- func ReturnSuccessResponse(response http.ResponseWriter, request *http.Request, message string)
- func ReturnSuccessResponseWithJson(response http.ResponseWriter, request *http.Request, res interface{}, ...)
- func SanitizeRelayedNodesForUpdate(gatewayID string, requested []string, priorMapKeys map[string]struct{}) []string
- func SaveExtClient(ctx context.Context, extclient *models.ExtClient) error
- func SchemaEnrollmentKeyFromModels(key models.EnrollmentKey) *schema.EnrollmentKey
- func SecurityCheck(reqAdmin bool, next http.Handler) http.HandlerFunc
- func SelectDeviceExitNode(ctx context.Context, user *schema.User, host *schema.Host, ...) (*models.DeviceExitNode, error)
- func SetDNSOnWgConfig(gwNode *models.Node, extclient *models.ExtClient)
- func SetDefaultGw(node models.Node, peerUpdate models.HostPeerUpdate) models.HostPeerUpdate
- func SetEgressDomainAnsForDomain(e *schema.Egress, domain string, ans []string)
- func SetEgressDomainAnsForDomains(e *schema.Egress, domains, ans []string)
- func SetInternetGw(node *models.Node, req models.InetNodeReq)
- func SetJWTSecret()
- func SetNetworkNodesLastModified(ctx context.Context, networkName string) error
- func SetNodeSelectedInternetEgress(node *models.Node, egressID string, useTcpUplink bool) error
- func SetOAuthSecret(secret string) error
- func SetRelayedNodes(setRelayed bool, relay string, relayed []string) []models.Node
- func SetState(scope scope.Scope, scopeID, appName, state string) error
- func SetVerbosity(logLevel int)
- func SmtpSkipTlsVerify(ctx context.Context) bool
- func SoleOrganization(ctx context.Context) (*schema.Organization, error)
- func SoleTenant(ctx context.Context) (*schema.Tenant, error)
- func SortAclEntrys(acls []models.Acl)
- func SortApiHosts(unsortedHosts []models.ApiHost)
- func SortApiNodes(unsortedNodes []models.ApiNode)
- func SortDNSEntrys(unsortedDNSEntrys []models.DNSEntry)
- func SortExtClient(unsortedExtClient []models.ExtClient)
- func SortNetworks(unsortedNetworks []schema.Network)
- func SortUsers(unsortedUsers []models.ReturnUser)
- func StartCPUProfiling() *os.File
- func StartHookManager(ctx context.Context, wg *sync.WaitGroup)
- func StartMemProfiling()
- func StopCPUProfiling(f *os.File)
- func StopHook(hookID string)
- func StoreHostPeerUpdate(ctx context.Context, hostID string, peerUpdate models.HostPeerUpdate)
- func StoreJWTSecret(privateKey string) error
- func StringDifference(a, b []string) []string
- func StringSliceContains(slice []string, item string) bool
- func SubscribeMetricExportIntervalReset(ctx context.Context) <-chan struct{}
- func SyncClearedExitNodeFields(dst, src *models.Node)
- func SyncDevice(host *schema.Host) error
- func Telemetry(ctx context.Context) string
- func TimerCheckpoint() error
- func ToReturnUser(user *schema.User) models.ReturnUser
- func ToUserEventLog(ctx context.Context, user *schema.User) models.UserEventLog
- func ToggleExtClientConnectivity(ctx context.Context, client *models.ExtClient, enable bool) (models.ExtClient, error)
- func Tokenize(ctx context.Context, k *schema.EnrollmentKey, serverAddr string) error
- func TransferDeviceHostOwnership(ctx context.Context, host *schema.Host, newOwner string) error
- func TryToUseEnrollmentKey(ctx context.Context, k *schema.EnrollmentKey) bool
- func UniqueAclPolicyTags(tags []models.AclPolicyTag) []models.AclPolicyTag
- func UniqueIPNetList(ipnets []net.IPNet) []net.IPNet
- func UniqueIPNetStrList(ipnets []string) []string
- func UniquePolicies(items []models.Acl) []models.Acl
- func UniqueStrings(input []string) []string
- func UnlinkNetworkAndTagsFromEnrollmentKeys(ctx context.Context, network string, delete bool) error
- func UnsetInternetGw(ctx context.Context, node *models.Node)
- func UpdateAcl(ctx context.Context, newAcl, acl models.Acl) error
- func UpdateEnrollmentKey(ctx context.Context, keyValue string, updates *models.APIEnrollmentKey) (*schema.EnrollmentKey, error)
- func UpdateExtClient(old *models.ExtClient, update *models.CustomExtClient) models.ExtClient
- func UpdateHost(ctx context.Context, newHost, currentHost *schema.Host)
- func UpdateHostFromClient(ctx context.Context, newHost, currHost *schema.Host) (isEndpointChanged, sendPeerUpdate bool)
- func UpdateHostNetwork(h *schema.Host, network string, add bool) (*models.Node, error)
- func UpdateHostNode(ctx context.Context, h *schema.Host, newNode *models.Node) (publishDeletedNodeUpdate, publishPeerUpdate bool, ...)
- func UpdateNetwork(ctx context.Context, currentNetwork, newNetwork *schema.Network) error
- func UpdateNode(currentNode *models.Node, newNode *models.Node) error
- func UpdateNodeCheckin(nodeID string) error
- func UpdateRelayNodes(relay string, oldNodes []string, newNodes []string) []models.Node
- func UpdateRelayed(ctx context.Context, currentNode, newNode *models.Node)
- func UpdateUser(ctx context.Context, userchange, _user *schema.User) (*schema.User, error)
- func UpsertAcl(ctx context.Context, acl models.Acl) error
- func UpsertNode(newNode *models.Node) error
- func UpsertServerSettings(ctx context.Context, s models.ServerSettings) error
- func UpsertUser(_user schema.User) error
- func UpsertUserSettings(username string, userSettings models.UserSettings) error
- func UserHasAccessToNetwork(ctx context.Context, user *schema.User, network string) bool
- func ValidateAndApproveUserInvite(ctx context.Context, email, code string) error
- func ValidateCreateAclReq(ctx context.Context, req models.Acl) error
- func ValidateDNSCreate(ctx context.Context, entry models.DNSEntry) error
- func ValidateDNSUpdate(ctx context.Context, change models.DNSEntry, entry models.DNSEntry) error
- func ValidateDomain(domain string) bool
- func ValidateEgressAppNATMode(e schema.Egress) error
- func ValidateEgressCIDR(network *schema.Network, cidr string) error
- func ValidateEgressGateway(gateway models.EgressGatewayRequest) error
- func ValidateEgressProOnlyFeatures(e schema.Egress) error
- func ValidateEgressRange(ctx context.Context, netID string, ranges []string) error
- func ValidateEgressReqProLimits(req *models.EgressReq) error
- func ValidateInetGwReq(ctx context.Context, node *schema.Node, req models.InetNodeReq, update bool) error
- func ValidateInternetEgressRoutingNode(node *models.Node) error
- func ValidateNetwork(ctx context.Context, network *schema.Network, isUpdate bool) error
- func ValidateNewSettings(ctx context.Context, req models.ServerSettings) error
- func ValidateParams(nodeid, netid string) (models.Node, error)
- func ValidateRelay(ctx context.Context, relay models.RelayRequest, update bool) error
- func ValidateUser(user *schema.User) error
- func VerifyAuthRequest(ctx context.Context, authRequest models.UserAuthParams, appName string) (string, error)
- func VerifyDeviceHostAccess(ctx context.Context, username, hostIDStr string) (*schema.Host, error)
- func VerifyHostToken(ctx context.Context, tokenString string) (hostID string, mac string, network string, err error)
- func VerifyOTPAuthURL(url, signature string) bool
- func VerifyUserToken(ctx context.Context, tokenString string) (username string, issuperadmin, isadmin bool, err error)
- func VersionLessThan(v1, v2 string) (bool, error)
- func WrapHook(hook func() error) models.HookFunc
- type ApiErrorType
- type CleanupUserRefsFunc
- type GlobalNs
- type MetricsMonitor
- type OSInfo
- type ServerSyncType
Constants ¶
const ( DashboardApp = "dashboard" NetclientApp = "netclient" NetmakerDesktopApp = "netmaker-desktop" )
const ( FallbackVNATPool = "198.18.0.0/15" VNATPoolPrefixLen = 22 DefaultSitePrefixV4 = 24 CgnatCIDR = "100.64.0.0/10" )
const ( MasterUser = "masteradministrator" Forbidden_Msg = "forbidden" )
const ( // ZOMBIE_TIMEOUT - timeout in hours for checking zombie status ZOMBIE_TIMEOUT = 6 // ZOMBIE_DELETE_TIME - timeout in minutes for zombie node deletion ZOMBIE_DELETE_TIME = 10 )
const DeviceHostIDHeader = "X-Host-ID"
const (
GooglePublicNameserverName = "Google Public DNS"
)
const KUBERNETES_LISTEN_PORT = 31821
KUBERNETES_LISTEN_PORT - starting port for Kubernetes in order to use NodePort range
const KUBERNETES_SERVER_MTU = 1024
KUBERNETES_SERVER_MTU - ideal mtu for kubernetes deployments right now
const MinVersion = "v0.17.0"
const StaleStatusCheckInterval = 5 * time.Minute
StaleStatusCheckInterval - how often MarkStaleNodesOffline scans the nodes table looking for nodes whose last check-in is older than models.LastCheckInThreshold.
Variables ¶
var ( CreateDefaultTags = func(ctx context.Context, netID schema.NetworkID) {} DeleteAllNetworkTags = func(ctx context.Context, networkID schema.NetworkID) {} IsUserAllowedToCommunicate = func(ctx context.Context, userName string, peer models.Node) (bool, []models.Acl) { return false, []models.Acl{} } RemoveUserFromAclPolicy = func(ctx context.Context, userName string) {} EnsureDefaultUserGroupNetworkPolicies = func(ctx context.Context, old, new *schema.UserGroup) error { return nil } GetGroupNetworksMap = func(ctx context.Context, group *schema.UserGroup) (map[schema.NetworkID]schema.Network, error) { return nil, nil } )
var ( // EnrichDeviceNetworksWithJIT adds JIT fields to device network responses (Pro). EnrichDeviceNetworksWithJIT = func(ctx context.Context, _ *schema.User, _ []schema.Network, networks []models.DeviceNetwork) []models.DeviceNetwork { return networks } // PublishHostRegistrationUpdates notifies peers after host network join (wired from mq). PublishHostRegistrationUpdates = func(ctx context.Context, _ *schema.Host) error { return nil } // RequestHostPullUpdate asks a host to pull config (wired from mq). RequestHostPullUpdate = func(_ *schema.Host) error { return nil } // JoinHostToNetworks adds a host to networks (wired from auth). JoinHostToNetworks = func(ctx context.Context, _ models.EnrollmentKey, _ *schema.Host, _ string) {} // ProvisionDeviceHostMessaging creates broker credentials for a new device host (wired from mq). ProvisionDeviceHostMessaging = func(_ *schema.Host) error { return nil } // CleanupDeviceHostForOwnershipTransfer removes prior user network state before host re-bind (wired from mq). CleanupDeviceHostForOwnershipTransfer = DefaultCleanupDeviceHostForOwnershipTransfer )
var ( IPv4Network = "0.0.0.0/0" IPv6Network = "::/0" )
var ( // ErrHostExists error indicating that host exists when trying to create new host ErrHostExists = errors.New("host already exists") ErrInvalidHostID = errors.New("invalid host id") ErrHostLimitExceeded = errors.New("host limit reached for this tenant, please upgrade your license") )
var ( // ResetAutoRelay - function to reset autorelayed peers on this node ResetAutoRelay = func(ctx context.Context, autoRelayNode *models.Node) error { return nil } // ResetAutoRelayedPeer - removes relayed peers for node ResetAutoRelayedPeer = func(ctx context.Context, failedOverNode *models.Node) error { return nil } // GetAutoRelayPeerIps - gets autorelay peerips GetAutoRelayPeerIps = func(ctx context.Context, peer, node *models.Node) []net.IPNet { return []net.IPNet{} } // SetAutoRelay - sets autorelay flag on the node SetAutoRelay = func(node *models.Node) { node.IsAutoRelay = false } )
var ( ErrInvalidJwtValidityDuration = errors.New("invalid jwt validity duration") ErrFlowLogsNotSupported = errors.New("flow logs not supported") ErrInvalidIPDetectionInterval = errors.New("invalid ip detection interval (must be greater than or equal to 15s)") )
var AddGlobalGroupOnRoleUpgrade = func(oldRole, newRole schema.UserRoleID, groups map[schema.UserGroupID]struct{}) {
}
var AddGlobalNetRolesToAdmins = func(u *schema.User) {}
var AdminPermissionTemplate = schema.UserRole{ ID: schema.AdminRole, Default: true, TenantGlobalAccess: true, }
var AssignVirtualRangeToEgress = func(nw *schema.Network, eg *schema.Egress) error { return nil }
var CanUserCreateNetwork = func(ctx context.Context, username string) bool { return true }
var CheckIfAnyPolicyisUniDirectional = func(targetNode models.Node, acls []models.Acl) bool { return false }
var CheckJITAccess = func(context.Context, string, string) (bool, *schema.JITGrant, error) { return true, nil, nil }
var CheckPostureViolations = func(ctx context.Context, d models.PostureCheckDeviceInfo, network schema.NetworkID) (v []models.Violation, level schema.Severity) { return []models.Violation{}, schema.SeverityUnknown }
var CheckPostureViolationsForHost = func(ctx context.Context, host *schema.Host, tags map[models.TagID]struct{}, network schema.NetworkID, skipAutoUpdate bool) ([]models.Violation, schema.Severity) { if host == nil { return []models.Violation{}, schema.SeverityUnknown } return CheckPostureViolations(ctx, models.PostureCheckDeviceInfo{ ClientLocation: host.CountryCode, ClientVersion: host.Version, OS: host.OS, OSFamily: host.OSFamily, OSVersion: host.OSVersion, KernelVersion: host.KernelVersion, AutoUpdate: host.AutoUpdate, SkipAutoUpdate: skipAutoUpdate, Tags: tags, HostID: host.ID.String(), }, network) }
var CheckUIHostReadAccess = func(r *http.Request, host *schema.Host) error { return nil }
CheckUIHostReadAccess verifies a dashboard user may read the given host. Overridden in Pro to enforce network-scoped host access.
var CleanupGwsMigration = func(ctx context.Context) {}
var ClientLimitExceeded = func(ctx context.Context) bool { return false }
var CreateDefaultNetworkRolesAndGroups = func(ctx context.Context, netID schema.NetworkID, username string) {}
var CreateDefaultUserPolicies = func(ctx context.Context, netID schema.NetworkID) { if netID.String() == "" { return } if !IsAclExists(ctx, fmt.Sprintf("%s.%s", netID, "all-users")) { defaultUserAcl := models.Acl{ ID: fmt.Sprintf("%s.%s", netID, "all-users"), Default: true, Name: "All Users", MetaData: "This policy gives access to everything in the network for an user", NetworkID: netID, Proto: models.ALL, ServiceType: models.Any, Port: []string{}, RuleType: models.UserPolicy, Src: []models.AclPolicyTag{ { ID: models.UserAclID, Value: "*", }, }, Dst: []models.AclPolicyTag{{ ID: models.NodeTagID, Value: "*", }}, AllowedDirection: models.TrafficDirectionUni, Enabled: true, CreatedBy: "auto", CreatedAt: time.Now().UTC(), } InsertAcl(ctx, defaultUserAcl) } }
var DeleteNetworkRoles = func(ctx context.Context, netID string) {}
var DeleteNodeMetricsFromPeers = func(context.Context, string) {}
var (
DeleteNodesCh = make(chan *models.Node, 100)
)
var DeleteRole = func(ctx context.Context, r schema.UserRoleID, force bool) error { return nil }
var EgressLimitExceeded = func(ctx context.Context) bool { return false }
var EmailInit = func(ctx context.Context) {}
var EnforceLimits = func(ctx context.Context) bool { return false }
var EnrollmentErrors = struct { InvalidCreate error NoKeyFound error InvalidKey error NoUsesRemaining error FailedToTokenize error FailedToDeTokenize error }{ InvalidCreate: fmt.Errorf("failed to create enrollment key. paramters invalid"), NoKeyFound: fmt.Errorf("no enrollmentkey found"), InvalidKey: fmt.Errorf("invalid key provided"), NoUsesRemaining: fmt.Errorf("no uses remaining"), FailedToTokenize: fmt.Errorf("failed to tokenize"), FailedToDeTokenize: fmt.Errorf("failed to detokenize"), }
EnrollmentErrors - struct for holding EnrollmentKey error messages
var EnterpriseCheckFuncs []func(ctx context.Context, wg *sync.WaitGroup)
EnterpriseCheckFuncs - can be set to run functions for EE
var ErrClientLimitExceeded = errors.New("client limit reached for this tenant, please upgrade your license")
var ErrEgressLimitExceeded = errors.New("egress limit reached for this tenant, please upgrade your license")
var ErrEgressProOnlyFeature = errors.New("domain and app egress require Netmaker Pro")
ErrEgressProOnlyFeature is returned when domain or app egress is used on Community Edition.
var ErrIngressLimitExceeded = errors.New("gateway limit reached for this tenant, please upgrade your license")
var ErrNetworkLimitExceeded = errors.New("network limit reached for this tenant, please upgrade your license")
var ErrUnknownEgressPreset = errors.New("unknown egress preset_id")
ErrUnknownEgressPreset is returned when preset_id does not match the catalog.
var ErrUserLimitExceeded = errors.New("user limit reached for this tenant, please upgrade your license")
var ErrVirtualNATNotForEgressApps = errors.New("virtual NAT is not supported for egress apps")
ErrVirtualNATNotForEgressApps is returned when virtual NAT is requested for a preset egress app.
var FilterNetworksByRole = func(ctx context.Context, allnetworks []schema.Network, user *schema.User) []schema.Network {
return allnetworks
}
var GetDeploymentMode = func() string {
return "self-hosted"
}
var GetEgressUserRulesForNode = func(ctx context.Context, targetnode *models.Node, rules map[string]models.AclRule) map[string]models.AclRule { return rules }
var GetFeatureFlags = func(ctx context.Context) models.FeatureFlags { return models.FeatureFlags{} }
var GetFilteredNodesByUserAccess = func(user *schema.User, nodes []models.Node) (filteredNodes []models.Node) {
return
}
var GetFwRulesForNodeAndPeerOnGw = getFwRulesForNodeAndPeerOnGw
var GetFwRulesForUserNodesOnGw = func(ctx context.Context, node models.Node, nodes []models.Node) (rules []models.FwRule) { return }
var GetMetrics = func(context.Context, string) (*models.Metrics, error) { var metrics models.Metrics return &metrics, nil }
var GetNameserversForHost = getNameserversForHost
var GetNameserversForNode = getNameserversForNode
var GetNodeStatus = func(ctx context.Context, node *models.Node, t bool) {
getNodeCheckInStatus(node, t)
}
var GetPostureCheckDeviceInfoByNode = func(ctx context.Context, node *models.Node) (d models.PostureCheckDeviceInfo) {
return
}
var GetTagMapWithNodesByNetwork = getTagMapWithNodesByNetwork
var GetUserAclRulesForNode = func(ctx context.Context, targetnode *models.Node, rules map[string]models.AclRule) map[string]models.AclRule { return rules }
var GetUserGroup = func(ctx context.Context, groupId schema.UserGroupID) (userGrps schema.UserGroup, err error) {
return
}
var GlobalNsList = map[string]GlobalNs{ "Google": { ID: "Google", IPs: []string{ "8.8.8.8", "8.8.4.4", "2001:4860:4860::8888", "2001:4860:4860::8844", }, }, "Cloudflare": { ID: "Cloudflare", IPs: []string{ "1.1.1.1", "1.0.0.1", "2606:4700:4700::1111", "2606:4700:4700::1001", }, }, "Quad9": { ID: "Quad9", IPs: []string{ "9.9.9.9", "149.112.112.112", "2620:fe::fe", "2620:fe::9", }, }, }
var HookCommandCh = make(chan models.HookCommand, 10)
HookCommandCh - channel to send commands to hooks (reset/stop)
var HookManagerCh = make(chan models.HookDetails, 3)
HookManagerCh - channel to add any new hooks
var HostLimitExceeded = func(ctx context.Context) bool { return false }
var IngressLimitExceeded = func(ctx context.Context) bool { return false }
var InitialiseNetworkRoles = func(ctx context.Context) {}
var InitialiseRoles = userRolesInit
var IntialiseGroups = func(ctx context.Context) {}
var IsAclPolicyValid = func(ctx context.Context, acl models.Acl) (err error) { if acl.AllowedDirection == models.TrafficDirectionUni { return errors.New("uni traffic flow not allowed on CE") } switch acl.RuleType { case models.DevicePolicy: for _, srcI := range acl.Src { if srcI.Value == "*" { continue } if srcI.ID == models.NodeTagID && srcI.Value == fmt.Sprintf("%s.%s", acl.NetworkID.String(), models.GwTagName) { continue } if err = checkIfAclTagisValid(ctx, acl, srcI, true); err != nil { return err } } for _, dstI := range acl.Dst { if dstI.Value == "*" { continue } if dstI.ID == models.NodeTagID && dstI.Value == fmt.Sprintf("%s.%s", acl.NetworkID.String(), models.GwTagName) { continue } if err = checkIfAclTagisValid(ctx, acl, dstI, false); err != nil { return } } default: return errors.New("unknown acl policy type " + string(acl.RuleType)) } if err := NormalizeAndValidateAclEgressIPs(&acl); err != nil { return err } return nil }
var IsMSP = func(ctx context.Context) bool { return false }
var IsNetworkAdmin = func(ctx context.Context, user *schema.User, networkID string) bool { return false }
var IsOAuthConfigured = func(context.Context) bool { return false }
var IsPeerAllowed = func(ctx context.Context, node, peer models.Node, checkDefaultPolicy bool) bool { var nodeId, peerId string if node.IsStatic { nodeId = node.StaticNode.ClientID node = models.ConvertToStaticNode(node.StaticNode) } else { nodeId = node.ID.String() } if peer.IsStatic { peerId = peer.StaticNode.ClientID peer = models.ConvertToStaticNode(peer.StaticNode) } else { peerId = peer.ID.String() } peerTags := make(map[models.TagID]struct{}) nodeTags := make(map[models.TagID]struct{}) nodeTags[models.TagID(nodeId)] = struct{}{} peerTags[models.TagID(peerId)] = struct{}{} if peer.IsGw { peerTags[models.TagID(fmt.Sprintf("%s.%s", peer.Network, models.GwTagName))] = struct{}{} } if node.IsGw { nodeTags[models.TagID(fmt.Sprintf("%s.%s", node.Network, models.GwTagName))] = struct{}{} } if checkDefaultPolicy { defaultPolicy, err := GetDefaultPolicy(ctx, schema.NetworkID(node.Network), models.DevicePolicy) if err == nil { if defaultPolicy.Enabled { return true } } } policies := ListDevicePolicies(ctx, schema.NetworkID(peer.Network)) srcMap := make(map[string]struct{}) dstMap := make(map[string]struct{}) defer func() { srcMap = nil dstMap = nil }() for _, policy := range policies { if !policy.Enabled { continue } if IsEgressRoutingPolicyAllowedForNodes(policy, node, peer) { return true } srcMap = ConvAclTagToValueMap(policy.Src) dstMap = ConvAclTagToValueMap(policy.Dst) for _, dst := range policy.Dst { if dst.ID == models.EgressID { e := schema.Egress{ID: dst.Value} err := e.Get(ctx) if err == nil && e.Status { for nodeID := range e.Nodes { dstMap[nodeID] = struct{}{} } } } } if CheckTagGroupPolicy(srcMap, dstMap, node, peer, nodeTags, peerTags) { return true } } return false }
var IsUserAllowedToJoinNetwork = defaultIsUserAllowedToJoinNetwork
IsUserAllowedToJoinNetwork reports whether username may join the given network. network may be the network name (netid) or UUID. ctx should carry tenant scope so User.Get can load PlatformRoleID and UserGroups from tenant_memberships_v1; if missing, DefaultScope is applied.
var LoadMetricsIntoCache = func(ctx context.Context) error { return nil }
var LogEvent = func(ctx context.Context, a *models.Event) {}
var NetworkHook models.HookFunc = func(params ...interface{}) error { if len(params) != 1 { return errors.New("invalid number of params") } tenantID, _ := params[0].(string) if len(tenantID) == 0 { return errors.New("invalid tenant id") } ctx := scope.WithContext(db.WithContext(context.TODO()), scope.TenantScope, tenantID) networks, err := (&schema.Network{}).ListAll(ctx) if err != nil { return err } allNodes, err := GetAllNodes(ctx) if err != nil { return err } for _, network := range networks { if !network.AutoRemove || network.AutoRemoveThreshold == 0 { continue } nodes := GetNetworkNodesMemory(allNodes, network.Name) for _, node := range nodes { if !node.Connected { continue } exists := false for _, tagI := range network.AutoRemoveTags { if tagI == "*" { exists = true break } if _, ok := node.Tags[models.TagID(tagI)]; ok { exists = true break } } if !exists { continue } if time.Since(node.LastCheckIn) > time.Duration(network.AutoRemoveThreshold)*time.Minute { if err := DeleteNode(ctx, &node, true); err != nil { continue } node.PendingDelete = true node.Action = schema.NODE_DELETE DeleteNodesCh <- &node host := &schema.Host{ID: node.HostID} if err := host.Get(ctx); err == nil && len(host.Nodes) == 0 { (&schema.Host{ID: host.ID}).Delete(ctx) } } } } return nil }
var NetworkLimitExceeded = func(ctx context.Context) bool { return false }
var NetworkPermissionsCheck = func(username string, r *http.Request) error { return nil }
var OrgAdminPermissionTemplate = schema.UserRole{ ID: schema.OrgAdmin, Default: true, OrgGlobalAccess: true, }
var OrgOwnerPermissionTemplate = schema.UserRole{ ID: schema.OrgOwner, Default: true, OrgGlobalAccess: true, }
var PlatformRoleRequiresGroupEnforcement = func(role schema.UserRoleID) bool { return false }
var PublishExitClientsFailOpen = func(ctx context.Context, clients []models.Node) {}
PublishExitClientsFailOpen is wired from mq to push fail-open peer updates to exit clients before their routing node is removed from the mesh.
var PublishPeerUpdateAfterExitNodeChange = func(ctx context.Context) {}
PublishPeerUpdateAfterExitNodeChange notifies peers after exit-node selection changes (wired from mq).
var PublishServerSync func(ctx context.Context, syncType ServerSyncType)
PublishServerSync is set by the mq package at startup to broadcast sync signals to peer servers in HA mode. The callback avoids a circular import (logic -> mq).
var ResetAuthProvider = func(context.Context) {}
var ResetIDPSyncHook = func(context.Context) {}
var RunPostureChecksForTenant = func(ctx context.Context) error { return nil }
var SetPeerMetricsDisconnected = func(context.Context, string) {}
var SettingsMutex = &sync.RWMutex{}
var StartFlowCleanupLoop = func() {}
var StopFlowCleanupLoop = func() {}
var StripGroupsOnRoleDowngrade = func(oldRole, newRole schema.UserRoleID, groups map[schema.UserGroupID]struct{}) {
}
var SuperAdminPermissionTemplate = schema.UserRole{ ID: schema.SuperAdminRole, Default: true, TenantGlobalAccess: true, }
var SyncFromIDP = func(context.Context) error { return nil }
SyncHostEDRState refreshes EDR posture state for a host (no-op in community).
SyncHostMDMState refreshes MDM posture state for a host (no-op in community).
var TenantPermissionsCheck = func(username string, r *http.Request) error { return nil }
var TriggerCollectMetrics = func(hostID, nodeID, reason string) {}
TriggerCollectMetrics - asks the client to push metrics now. Overridden in Pro. reason is a short label (e.g. "join", "reconnect", "checkin_recovered") used for logging.
var UpdateUserGwAccess = func(ctx context.Context, currentUser, changeUser *schema.User) {}
var UserHasDeviceNetworkWriteAccess = defaultUserHasDeviceNetworkWriteAccess
UserHasDeviceNetworkWriteAccess reports whether the user may mutate device network membership/state (join, leave, exit-node selection). CE defaults to network access; Pro overrides with scope checks that deny read-only roles.
var UserHasGlobalNetworksAdminMembership = func(user *schema.User) bool { return false }
var UserHasNetworkGroupAccess = func(ctx context.Context, user *schema.User, networkID string) bool { return false }
var UserLimitExceeded = func(ctx context.Context) bool { return false }
var UserSubjectToNetworkJIT = func(context.Context, string, *schema.User) bool { return false }
UserSubjectToNetworkJIT reports whether the user must satisfy JIT for client-app extclient creates on the network (JIT enabled + in unscoped / allowlisted groups).
var ValidateEgressReq = validateEgressReq
var ValidateNameserverReq = validateNameserverReq
Functions ¶
func AddEgressInfoToPeerByAccess ¶ added in v0.99.0
func AddHook ¶
func AddHook(ifaceToAdd interface{})
AddHook - adds a hook function to run every 24hrs
func AddSSOStateCleanupHook ¶ added in v1.5.1
func AddSSOStateCleanupHook()
AddSSOStateCleanupHook registers a periodic cleanup of expired SSO states
func AddStaticNodestoList ¶ added in v0.26.0
func AddStatusToNodes ¶ added in v0.30.0
func AllDomainAnsFromEgress ¶ added in v1.6.0
AllDomainAnsFromEgress returns the flattened union of per-domain answers (ACL/routing).
func AllocateUniquePoolFromFallback ¶ added in v1.5.1
func AllocateUniquePoolFromFallback(pool *net.IPNet, newPrefixLen int, allocated map[string]struct{}, seed string) string
AllocateUniquePoolFromFallback allocates a unique subnet of the given prefix length from the fallback pool, skipping any subnets already present in the allocated map.
func AllocateUniqueVNATPool ¶ added in v1.5.1
AllocateUniqueVNATPool allocates a unique Virtual NAT pool for a network, ensuring it doesn't conflict with pools already assigned to other networks.
func AppendEgressPolicyRange ¶ added in v1.7.0
AppendEgressPolicyRange appends CIDRs for ACL/firewall from an egress. Internet egress stores Range as "*" which is not a CIDR; expand to 0.0.0.0/0 and ::/0 so internet policies actually install destinations on the exit node.
func ApplyConfiguredDomainsToEgress ¶ added in v1.6.0
ApplyConfiguredDomainsToEgress sets Domains on the egress record.
func ApplyEgressPresetToEgressReq ¶ added in v1.6.0
ApplyEgressPresetToEgressReq merges catalog defaults into req. Rules: explicit non-empty name, description, and domains in req override preset. PresetID must already be a known id.
func ApplyExtClientInternetEgressSelection ¶ added in v1.7.0
func ApplyExtClientInternetEgressSelection(ctx context.Context, client *models.ExtClient, gatewayNodeID string, update *models.CustomExtClient) error
ApplyExtClientInternetEgressSelection resolves use_internet_egress on create/update or validates selected_internet_egress_id. Opt-in is per config file.
Legacy desktop/RAC apps omit use_internet_egress. When those clients connect through a gateway that is also an exit node, the gateway's internet egress is auto-selected so AllowedIPs include 0.0.0.0/0 (previous IsInternetGateway behavior). Dashboard config files (no device_id / remote_access_client_id) remain opt-in only.
func AssignNodeExitNode ¶ added in v1.7.0
func AssignNodeExitNode(ctx context.Context, network, nodeID, egressID string, useTcpUplink bool) (*models.DeviceExitNode, error)
AssignNodeExitNode sets or clears the internet egress for a node (admin; no ACL checks). useTcpUplink opts the client into TCP uplink to the exit routing gateway when that gateway has TCP proxy enabled; ignored when clearing the exit.
func AssignVirtualNATDefaults ¶ added in v1.5.1
AssignVirtualNATDefaults determines safe defaults based on VPN CIDR
func AssociateNodeToHost ¶
AssociateNodeToHost - associates a node with a host and persists both.
func AutoUpdateEnabled ¶ added in v0.99.0
AutoUpdateEnabled returns a boolean indicating whether netclient auto update is enabled or disabled default is enabled
func CancelDeviceNetworkJoin ¶ added in v1.7.0
func CancelDeviceNetworkJoin(ctx context.Context, user *schema.User, host *schema.Host, networkID string) error
CancelDeviceNetworkJoin removes a pending join approval request without leaving a joined network.
func CheckEndpoint ¶
CheckEndpoint - checks if an endpoint is valid
func CheckHostPorts ¶
CheckHostPorts checks host endpoints to ensures that hosts on the same server with the same endpoint have different listen ports in the case of 64535 hosts or more with same endpoint, ports will not be changed
func CheckIfFileExists ¶
CheckIfFileExists - checks if file exists or not in the given path
func CheckTagGroupPolicy ¶ added in v0.99.0
func CheckZombies ¶
CheckZombies - checks if new node has same hostid as existing node if so, existing node is added to zombie node quarantine list also cleans up nodes past their expiration date
func CleanExpiredSSOStates ¶ added in v1.5.1
func CleanExpiredSSOStates() error
CleanExpiredSSOStates removes expired SSO state entries from the database to prevent unbounded table growth that degrades FetchRecord performance.
func CleanVersion ¶ added in v1.4.0
CleanVersion normalizes a version string safely for storage. - removes "v" or "V" prefix - trims whitespace - strips invalid trailing characters - preserves semver, prerelease, and build metadata
func CleanupOtherExtclients ¶ added in v1.5.1
CleanupOtherExtclients cleans up other clients owned by the same use for the same device and network.
func ClearEgressDomainAns ¶ added in v1.6.0
ClearEgressDomainAns clears per-domain answers.
func ClearExitNodeForDisconnect ¶ added in v1.7.0
ClearExitNodeForDisconnect clears the node's internet exit selection so a subsequent peer update can remove full-tunnel routes before disconnect. Returns true when a selection was cleared. Callers should sync related fields onto any in-flight node copy (SelectedInternetEgressID, InternetGwID, IsRelayed, RelayedBy) from the updated node.
func ClearNodesSelectedInternetEgress ¶ added in v1.7.0
ClearNodesSelectedInternetEgress clears SelectedInternetEgressID for all nodes that selected this egress.
func CompareIfaceSlices ¶ added in v1.1.0
CompareIfaceSlices compares two slices of Iface for deep equality (order-sensitive)
func CompareMaps ¶ added in v0.99.0
func CompareMaps[K comparable, V any](a, b map[K]V) bool
Compare any two maps with any key and value types
func ConfiguredDomainsForEgress ¶ added in v1.6.0
ConfiguredDomainsForEgress returns the user-configured hostname list from e.Domains (JSON). It does not read the legacy DB column "domain" (singular); that is migrated once in migrateEgressDomains.
func ContainsCIDR ¶ added in v0.24.3
func ContinueIfUserMatch ¶
func ContinueIfUserMatch(next http.Handler) http.HandlerFunc
func ContinueIfUserMatchOrAdmin ¶ added in v1.6.0
func ContinueIfUserMatchOrAdmin(next http.Handler) http.HandlerFunc
func ConvAclTagToValueMap ¶ added in v0.99.0
func ConvAclTagToValueMap(acltags []models.AclPolicyTag) map[string]struct{}
func ConvertModelsNodeToSchemaNode ¶ added in v1.6.0
func ConvertSchemaNodeToApiNode ¶ added in v1.6.0
func ConvertSchemaNodeToModelsNode ¶ added in v1.6.0
func ConvertSchemaNodeToModelsNodeWithContext ¶ added in v1.7.0
func CreateDefaultAclNetworkPolicies ¶ added in v0.26.0
CreateDefaultAclNetworkPolicies - create default acl network policies
func CreateDefaultNetworkEnrollmentKey ¶ added in v1.7.0
func CreateDefaultNetworkEnrollmentKey(ctx context.Context, networkName string) (*schema.EnrollmentKey, error)
CreateDefaultNetworkEnrollmentKey creates an unlimited default enrollment key for a network.
func CreateEgressGateway ¶
func CreateEgressGateway(gateway models.EgressGatewayRequest) (models.Node, error)
CreateEgressGateway - creates an egress gateway
func CreateEnrollmentKey ¶
func CreateEnrollmentKey(ctx context.Context, uses int, expiration time.Time, networks, tags []string, groups []models.TagID, unlimited bool, relay uuid.UUID, defaultKey, autoEgress, autoAssignGw bool) (*schema.EnrollmentKey, error)
CreateEnrollmentKey - creates a new enrollment key in db
func CreateFallbackNameserver ¶ added in v1.4.0
func CreateHost ¶
CreateHost - creates a host if not exist
func CreateInternetEgressForNode ¶ added in v1.7.0
func CreateInternetEgressForNode(ctx context.Context, node *models.Node, name, createdBy string) (*schema.Egress, error)
CreateInternetEgressForNode creates an internet-type egress with the given node as routing node.
func CreateNetwork ¶
CreateNetwork - creates a network in database
func CreatePreAuthToken ¶ added in v1.0.0
CreatePreAuthToken generate a jwt token to be used as intermediate token after primary-factor authentication but before secondary-factor authentication. It carries the same scope as the eventual auth token so that PreAuthCheck can confirm the token was issued for the scope it's being redeemed in.
func CreateUserAccessJwtToken ¶ added in v0.99.0
func CreateUserAccessJwtToken(ctx context.Context, username string, d time.Time, tokenID string) (response string, err error)
CreateUserJWT - creates a user jwt token
func CreateUserJWT ¶
func CreateUserJWT(ctx context.Context, username string, appName string) (response string, err error)
CreateUserJWT - creates a user jwt token
func DeTokenize ¶
DeTokenize - detokenizes a base64 encoded string and finds the associated enrollment key
func DefaultCleanupDeviceHostForOwnershipTransfer ¶ added in v1.7.0
DefaultCleanupDeviceHostForOwnershipTransfer removes pending joins and network nodes from a host.
func DeleteEgressGateway ¶
DeleteEgressGateway - deletes egress from node
func DeleteEnrollmentKey ¶
DeleteEnrollmentKey - deletes a given enrollment key by value
func DeleteExpiredNodes ¶
DeleteExpiredNodes - goroutine which deletes nodes which are expired
func DeleteExtClient ¶
DeleteExtClient - deletes an existing ext client
func DeleteExtClientAndCleanup ¶ added in v0.24.1
DeleteExtClientAndCleanup - deletes an existing ext client and update ACLs
func DeleteGatewayExtClients ¶
DeleteGatewayExtClients - deletes ext clients based on gateway (mac) of ingress node and network
func DeleteIngressGateway ¶
func DeleteIngressGateway(ctx context.Context, nodeid string) (models.Node, []models.ExtClient, error)
DeleteIngressGateway - deletes an ingress gateway
func DeleteInternetEgressesForRoutingNode ¶ added in v1.7.0
DeleteInternetEgressesForRoutingNode removes internet egress resources where nodeID is a routing node.
func DeleteNetwork ¶
DeleteNetwork - deletes a network
func DeleteNetworkDNS ¶ added in v1.6.0
func DeleteNetworkPolicies ¶ added in v0.90.0
DeleteNetworkPolicies - deletes all default network acl policies
func DeleteNodeByID ¶ added in v0.21.2
DeleteNodeByID - deletes a node from database
func DeleteOrgUser ¶ added in v1.7.0
func DeleteRelay ¶ added in v0.90.0
DeleteRelay - deletes a relay
func DeleteTenantUser ¶ added in v1.7.0
func DetachExitRoutingNode ¶ added in v1.7.0
DetachExitRoutingNode prepares a routing node for removal from the network: fails open RelayedBy / IsIGWClient for exit clients (keeps sticky SelectedInternetEgressID), removes the node from internet egress routing maps (egress resource is kept for reassignment), and returns affected clients for an ordered fail-open peer update.
func DisassociateAllNodesFromHost ¶
DisassociateAllNodesFromHost - deletes all nodes of the host. Performs reference cleanup and directly deletes each node record, bypassing host-association updates since the host itself is being removed.
func DisassociateNodeFromHost ¶ added in v1.7.0
DisassociateNodeFromHost - deletes a node and removes from host nodes should be the only way nodes are deleted as of 0.18
func DisplaceAutoRelayedNodes ¶ added in v1.5.1
DisplaceAutoRelayedNodes removes auto-assigned nodes from a disconnected gateway and returns the displaced nodes that need re-assignment.
func DoesHostExistInTheNetworkAlready ¶ added in v1.6.0
DoesHostExistInTheNetworkAlready checks if the host is in the network already. Must be called before creating the node. TODO: create (*orchestrator.NodeOrchestrator).ValidateCreateNode and move this there.
func DoesNodeHaveAccessToEgress ¶ added in v0.99.0
func DoesUserHaveAccessToEgress ¶ added in v1.1.0
func DomainAnsForDomain ¶ added in v1.6.0
DomainAnsForDomain returns resolved CIDRs for one configured domain.
func DomainAnsMapFromEgress ¶ added in v1.6.0
DomainAnsMapFromEgress returns domain -> resolved CIDRs from domain_ans_by_domain.
func EgressDomainsEqual ¶ added in v1.6.0
EgressDomainsEqual compares two domain lists as sets (order-independent).
func EnsureHostOwner ¶ added in v1.7.0
EnsureHostOwner sets OwnerUsername on the host when it is currently empty in the database. Uses a conditional update so concurrent callers cannot overwrite an existing owner.
func EnterpriseCheck ¶
EnterpriseCheck - Runs enterprise functions if presented
func ErrExitClientBlocksAutoRelayRole ¶ added in v1.7.0
ErrExitClientBlocksAutoRelayRole returns an error when an exit client tries to act as an auto-relay gateway. Exit routing nodes remain valid auto-relay targets.
func ErrExitNodeBlocksAutoRelay ¶ added in v1.7.0
ErrExitNodeBlocksAutoRelay returns an error when the node must not be auto-relayed (as victim/peer). Exit clients already have RelayedBy managed by exit selection; exit routing nodes must not be auto-relayed (same as manual relay). Exit routing nodes may still act as auto-relay gateways for other peers.
func ErrExitNodeBlocksGatewayOps ¶ added in v1.7.0
ErrExitNodeBlocksGatewayOps returns an error when the node must not use GW assign/unassign/auto-assign. Exit clients have RelayedBy managed by exit selection; exit routers cannot be gateway clients.
func ExitClientOverlayIPs ¶ added in v1.7.0
ExitClientOverlayIPs returns /32 and /128 overlay addresses for clients in peer.RelayedNodes and peer.InetNodeReq.InetNodeClientIDs, excluding excludeID.
func ExitClientOverlayIPsFromInetClients ¶ added in v1.7.0
ExitClientOverlayIPsFromInetClients returns overlay IPs for InetNodeClientIDs that are not already listed in RelayedNodes (RelayedAllowedIPs covers those).
func ExpandEgressRouteRanges ¶ added in v1.7.0
ExpandEgressRouteRanges maps an egress resource to concrete CIDR ranges for peer/firewall config. Internet egress expands "*" to 0.0.0.0/0 (and optionally ::/0).
func ExtClientUsesInternetEgress ¶ added in v1.7.0
ExtClientUsesInternetEgress reports whether the config file should route all traffic via its gateway exit node.
Using the gateway as an exit node is opt-in per client via SelectedInternetEgressID (the "Use gateway as exit node" toggle). It must NOT be forced on just because the gateway happens to be an internet gateway/exit node; clients that did not opt in should not get a full tunnel. Legacy full-tunnel clients are migrated to an explicit SelectedInternetEgressID, so no gateway-level fallback is needed.
func FailOpenAndDetachExitRoutingNode ¶ added in v1.7.0
FailOpenAndDetachExitRoutingNode detaches exit routing state for a node about to be removed, then pushes ordered fail-open peer updates to affected clients.
func FetchOAuthSecret ¶ added in v1.7.0
FetchOAuthSecret fetches secrets for oauth
func FilterOutIPs ¶ added in v1.2.0
FilterOutIPs removes ips in the filters map from the ips slice.
func FindInternetEgressByRoutingNode ¶ added in v1.7.0
func FindInternetEgressByRoutingNode(ctx context.Context, network, nodeID string) (*schema.Egress, error)
FindInternetEgressByRoutingNode returns an active internet egress that uses nodeID as a routing node.
func FirstInternetEgressRoutingNodeID ¶ added in v1.7.0
FirstInternetEgressRoutingNodeID returns a routing node ID from an internet egress.
func FlattenDomainAnsMap ¶ added in v1.6.0
FlattenDomainAnsMap returns a de-duplicated union of all resolved CIDRs in the map.
func FlushNodeCheckins ¶ added in v1.5.1
func FlushNodeCheckins()
FlushNodeCheckins - writes all buffered check-in updates to the DB in one batch. Called periodically (e.g., every 30s) to avoid per-checkin write lock contention.
func FormatError ¶
func FormatError(err error, errType ApiErrorType) models.ErrorResponse
FormatError - takes ErrorResponse and uses correct code
func GenerateNodeName ¶ added in v0.30.0
func GenerateOTPAuthURLSignature ¶ added in v1.0.0
func GetAclRuleForInetGw ¶ added in v0.99.0
func GetAclRulesForNode ¶ added in v0.30.0
func GetAllEnrollmentKeys ¶
func GetAllEnrollmentKeys(ctx context.Context) ([]schema.EnrollmentKey, error)
GetAllEnrollmentKeys - fetches all enrollment keys from DB
func GetAllExtClients ¶
GetAllExtClients - gets all ext clients from DB
func GetAllExtClientsWithStatus ¶ added in v0.99.0
func GetAllExtClientsWithStatus(ctx context.Context, status schema.NodeStatus) ([]models.ExtClient, error)
GetAllExtClientsWithStatus - returns all external clients with given status.
func GetAllHostsAPI ¶
GetAllHostsAPI - get's all the hosts in an API usable format
func GetAllHostsWithStatus ¶ added in v0.99.0
GetAllHostsWithStatus - returns all hosts with at least one node with given status.
func GetAllNodes ¶
GetAllNodes - returns all nodes in the DB
func GetAllNodesAPI ¶
GetAllNodesAPI - get all nodes for api usage
func GetAllNodesAPIWithLocation ¶ added in v1.0.0
GetAllNodesAPI - get all nodes for api usage
func GetAllRsrcIDForRsrc ¶ added in v1.1.0
func GetAllowedEmailDomains ¶ added in v0.99.0
GetAllowedEmailDomains - gets the allowed email domains for oauth signup
func GetAllowedIPs ¶
func GetAllowedIPs(ctx context.Context, node, peer *models.Node, metrics *models.Metrics) []net.IPNet
GetAllowedIPs - calculates the wireguard allowedip field for a peer of a node based on the peer and node settings
func GetAllowedIpForInetNodeClient ¶ added in v0.23.0
GetAllowedIpForInetNodeClient - get inet cidr for node using a inet gw. Dual-stack is decided from the exit peer host's public endpoints.
func GetAllowedIpsForRelayed ¶
func GetAllowedIpsForRelayed(ctx context.Context, relayed, relay *models.Node) (allowedIPs []net.IPNet)
GetAllowedIpsForRelayed - returns the peerConfig for a node relayed by relay
func GetAuditLogsRetentionPeriodInDays ¶ added in v1.7.0
func GetAuthProviderInfo ¶ added in v0.99.0
func GetAuthProviderInfo(settings models.ServerSettings) (pi []string)
GetAuthProviderInfo = gets the oauth provider info
func GetAzureTenant ¶ added in v0.99.0
GetAzureTenant - retrieve the azure tenant ID from env variable or config file
func GetCachedHostPeerUpdate ¶ added in v1.5.1
GetCachedHostPeerUpdate - returns a cached HostPeerUpdate if available.
func GetClientIP ¶ added in v1.0.0
func GetCurrentServerUsage ¶ added in v1.2.0
func GetCustomDNS ¶
GetCustomDNS - gets the custom DNS of a network
func GetDNSEntryNum ¶
GetDNSEntryNum - gets which entry the dns was
func GetDefaultDomain ¶ added in v0.99.0
GetDefaultDomain - get the default domain
func GetDefaultEnrollmentKeyForNetwork ¶ added in v1.6.0
func GetDefaultEnrollmentKeyForNetwork(ctx context.Context, network string) (*schema.EnrollmentKey, error)
GetDefaultEnrollmentKeyForNetwork returns the default enrollment key for a network.
func GetDefaultHosts ¶
GetDefaultHosts - retrieve all hosts marked as default from DB
func GetDefaultPolicy ¶ added in v0.26.0
func GetDefaultPolicy(ctx context.Context, netID schema.NetworkID, ruleType models.AclPolicyType) (models.Acl, error)
GetDefaultPolicy - fetches default policy in the network by ruleType
func GetDefaultTenantSettings ¶ added in v1.7.0
func GetDefaultTenantSettings() models.ServerSettings
func GetDeviceNetworks ¶ added in v1.7.0
func GetDeviceNetworks(ctx context.Context, user *schema.User, host *schema.Host) ([]models.DeviceNetwork, error)
GetDeviceNetworks returns networks accessible to the user with join/connection state for the host.
func GetDeviceSelectedExitNode ¶ added in v1.7.0
func GetDeviceSelectedExitNode(ctx context.Context, user *schema.User, host *schema.Host, networkID string) (*models.DeviceExitNode, error)
GetDeviceSelectedExitNode returns the currently selected exit node for the device on the network.
func GetEgressDefaultAllowAllFwRule ¶ added in v1.6.0
GetEgressDefaultAllowAllFwRule returns one bidirectional allow from the node's VPN (mesh) CIDR(s) to every egress LAN range this gateway advertises, for default all-resources device+user policies. Netclients use this to install a single mesh → LAN ACCEPT (e.g. 100.64.0.0/16 → 10.104.0.0/20).
func GetEgressDomainNSForNode ¶ added in v1.4.0
func GetEgressDomainsByAccessForUser ¶ added in v1.4.0
func GetEgressPresetByID ¶ added in v1.6.0
func GetEgressPresetByID(id string) (models.EgressPresetApp, bool)
GetEgressPresetByID returns a catalog entry by id.
func GetEgressRanges ¶ added in v0.90.0
func GetEgressRangesOnNetwork ¶
ExtClient.GetEgressRangesOnNetwork - returns the egress ranges on network of ext client. Internet egress (0.0.0.0/0, ::/0) is excluded here: full-tunnel is opt-in via SelectedInternetEgressID and is applied only by ExtClientUsesInternetEgress / GetExtclientAllowedIPs (and the matching config-file path).
func GetEgressRulesForNode ¶ added in v0.90.0
func GetEmaiSenderPassword ¶ added in v0.99.0
func GetEnrollmentKey ¶
GetEnrollmentKey - fetches a single enrollment key by value
func GetExtClient ¶
GetExtClient - gets a single ext client on a network
func GetExtClientByName ¶
GetExtClientByName - gets an ext client by name
func GetExtClientsByID ¶
GetExtClientsByID - gets the clients of attached gateway
func GetExtPeers ¶ added in v0.24.2
func GetExtPeers(ctx context.Context, node, peer *models.Node, addressIdentityMap map[string]models.PeerIdentity) ([]wgtypes.PeerConfig, []models.IDandAddr, []models.EgressNetworkRoutes, error)
func GetExtclientAllowedIPs ¶ added in v0.22.0
func GetExtclientDNS ¶ added in v0.22.0
GetExtclientDNS - gets all extclients dns entries
func GetFwRulesOnIngressGateway ¶ added in v0.26.0
func GetHostNetworks ¶
GetHostNetworks - fetches all the networks
func GetHostNodes ¶
GetHostNodes - fetches all nodes part of the host
func GetHostPeerInfo ¶ added in v0.90.0
GetHostPeerInfo - returns cached peer info for a host. Falls back to on-demand computation if the cache is not yet populated.
func GetIDPSyncInterval ¶ added in v0.99.0
GetIDPSyncInterval returns the interval at which the netmaker should sync data from IDP.
func GetIngressGwUsers ¶
func GetIngressGwUsers(node models.Node) (models.IngressGwUsers, error)
GetIngressGwUsers - lists the users having to access to ingressGW
func GetJwtSecretValue ¶ added in v1.7.0
GetJwtSecretValue fetches jwt secret from db
func GetJwtValidityDuration ¶ added in v0.99.0
GetJwtValidityDuration - returns the JWT validity duration in minutes
func GetJwtValidityDurationForClients ¶ added in v1.1.0
GetJwtValidityDurationForClients returns the JWT validity duration in minutes for clients.
func GetLoginMethodsForUser ¶ added in v1.7.0
GetLoginMethodsForUser returns available login options for the given username. Returns an empty slice (not an error) when the user is not found.
func GetManageDNS ¶ added in v0.99.0
GetManageDNS - if manage DNS enabled or not
func GetMetricInterval ¶ added in v0.99.0
GetMetricInterval - get the publish metric interval
func GetMetricIntervalInMinutes ¶ added in v0.99.0
GetMetricIntervalInMinutes returns the publish-to-exporter interval from server settings (dashboard), with fallback to servercfg / env when unset or invalid.
func GetMetricsPort ¶ added in v0.99.0
GetMetricsPort - get metrics port
func GetNetworkExtClients ¶
GetNetworkExtClients - gets the ext clients of given network
func GetNetworkNetworkCIDR4 ¶ added in v1.5.1
func GetNetworkNetworkCIDR6 ¶ added in v1.5.1
func GetNetworkNodes ¶
GetNetworkNodes - gets the nodes of a network
func GetNetworkNodesMemory ¶
GetNetworkNodesMemory - gets all nodes belonging to a network from list in memory
func GetNetworkNonServerNodeCount ¶
GetNetworkNonServerNodeCount - get number of network non server nodes
func GetNodeByHostRef ¶ added in v0.21.2
GetNodeByHostRef - gets the node by host id and network
func GetNodeCheckInStatus ¶ added in v0.90.0
func GetNodeCheckInStatus(node *schema.Node) schema.NodeStatus
func GetNodeDNS ¶
GetNodeDNS - gets the DNS of a network node
func GetNodeEgressInfo ¶ added in v0.99.0
func GetNodeExitNode ¶ added in v1.7.0
GetNodeExitNode returns the internet egress currently assigned to the node.
func GetNodesByIDs ¶ added in v1.6.0
GetNodesByIDs fetches all nodes whose IDs are in the given slice in a single preloaded query and returns them as a map keyed by node ID. IDs that don't resolve to a node row are simply absent from the result map.
This avoids the N+1 (and N^2) query patterns that arise when callers loop over peer IDs and call GetNodeByID per peer (e.g. status / connectivity checks driven by metrics).
func GetNodesStatusAPI ¶ added in v0.90.0
func GetNodesStatusAPI(nodes []models.Node) map[string]models.ApiNodeStatus
GetNodesStatusAPI - gets nodes status
func GetOnboardingStatus ¶ added in v1.6.0
GetOnboardingStatus reports whether the UI should show the first-network onboarding flow.
func GetOrgSettings ¶ added in v1.7.0
func GetOrgSettings(ctx context.Context) schema.OrganizationSettingsData
GetOrgSettings returns the organization settings for the organization scoped by ctx (resolving through the tenant if ctx is tenant-scoped).
func GetPeerListenPort ¶
GetPeerListenPort - given a host, retrieve it's appropriate listening port
func GetPeerUpdateForHost ¶
func GetPeerUpdateForHost(ctx context.Context, network string, host *schema.Host, allNodes []models.Node, deletedHost *schema.Host, deletedNode *models.Node, deletedClients []models.ExtClient) (hostPeerUpdate models.HostPeerUpdate, err error)
GetPeerUpdateForHost - gets the consolidated peer update for the host from all networks
func GetRacRestrictToSingleNetwork ¶ added in v0.99.0
GetRacRestrictToSingleNetwork - returns whether the feature to allow simultaneous network connections via RAC is enabled
func GetRecordKey ¶
GetRecordKey - get record key depricated
func GetRunningHooks ¶ added in v1.4.0
func GetRunningHooks() []string
GetRunningHooks - returns a list of currently running hook IDs
func GetSelectedInternetEgress ¶ added in v1.7.0
GetSelectedInternetEgress returns the internet egress selected by the node, if any and still valid.
func GetSenderEmail ¶ added in v0.99.0
func GetSenderUser ¶ added in v0.99.0
func GetServerConfig ¶ added in v0.99.0
func GetServerConfig(ctx context.Context) config.ServerConfig
GetServerConfig - gets the server config into memory from file or env
func GetServerInfo ¶ added in v0.99.0
func GetServerInfo(ctx context.Context) models.ServerConfig
GetServerInfo - gets the server config into memory from file or env
func GetServerSettings ¶ added in v0.99.0
func GetServerSettings(ctx context.Context) (s models.ServerSettings)
func GetServerSettingsFromEnv ¶ added in v0.99.0
func GetServerSettingsFromEnv() (s models.ServerSettings)
func GetSmtpHost ¶ added in v0.99.0
func GetSmtpPort ¶ added in v0.99.0
func GetStaticNodeIps ¶ added in v0.26.0
func GetStaticNodesByNetwork ¶ added in v0.26.0
func GetStunServers ¶ added in v0.99.0
func GetSuperAdmin ¶
func GetSuperAdmin(ctx context.Context) (models.ReturnUser, error)
GetSuperAdmin - fetches superadmin user
func GetTenantNetworkHookID ¶ added in v1.7.0
func GetUserInvite ¶ added in v0.25.0
func GetUserNameFromToken ¶ added in v0.25.0
func GetUserSettings ¶ added in v1.1.0
func GetUserSettings(username string) models.UserSettings
func GetVerbosity ¶ added in v0.99.0
func HasEgressDomainAns ¶ added in v1.6.0
HasEgressDomainAns is true when at least one resolved CIDR exists for any domain.
func HostExists ¶
HostExists - checks if given host already exists
func IfaceDelta ¶
IfaceDelta - checks if the new node causes an interface change
func InferEgressType ¶ added in v1.7.0
func InferEgressType(req *models.EgressReq) schema.EgressType
InferEgressType derives the egress type from request fields when Type is unset.
func InitNetworkHooks ¶ added in v1.4.0
func InternetEgressRanges ¶ added in v1.7.0
InternetEgressRanges returns the WireGuard/firewall ranges for an internet egress.
func InternetExitRoutingNodeID ¶ added in v1.7.0
InternetExitRoutingNodeID returns the node ID used for full-internet exit. Prefers SelectedInternetEgressID (source of truth). When a selection is set but the egress is unavailable (disabled/missing), returns "" so clients fail open to local internet while keeping the sticky selection — do not fall back to InternetGwID in that case. Legacy InternetGwID is only used when no selection is set.
func InvalidateHostPeerCaches ¶ added in v1.5.1
InvalidateHostPeerCaches clears both hostPeerInfoCache and hostPeerUpdateCache so they are rebuilt on next access or refresh.
func InvalidateServerSettingsCache ¶ added in v1.5.1
InvalidateServerSettingsCache clears the in-memory settings cache for the tenant scoped by ctx so the next GetServerSettings call re-reads from the database.
func IsAWSEgressPreset ¶ added in v1.6.0
IsAWSEgressPreset reports whether presetID refers to an AWS catalog entry.
func IsAclExists ¶ added in v0.26.0
IsAclExists - checks if acl exists
func IsAddressInCIDR ¶
IsAddressInCIDR - util to see if an address is in a cidr or not
func IsBase64 ¶
IsBase64 - checks if a string is in base64 format This is used to validate public keys (make sure they're base64 encoded like all public keys should be).
func IsBasicAuthEnabled ¶ added in v0.99.0
IsBasicAuthEnabled - checks if basic auth has been configured to be turned off
func IsDNSEntryValid ¶ added in v0.30.0
IsNetworkNameValid - checks if a netid of a network uses valid characters
func IsDomainBasedEgress ¶ added in v1.6.0
IsDomainBasedEgress is true when this egress has at least one configured logical domain.
func IsEgressAppEgress ¶ added in v1.6.0
IsEgressAppEgress reports whether the egress was created from a catalog preset (egress app).
func IsEgressDomainPattern ¶ added in v1.6.0
IsEgressDomainPattern returns true for a normal FQDN or a single-label wildcard prefix form (*.example.com).
func IsEgressInternetGateway ¶ added in v1.6.0
IsEgressInternetGateway is true when type is internet or range is "*" (full internet egress).
func IsEgressReqInternetGateway ¶ added in v1.6.0
IsEgressReqInternetGateway is true when the request uses type internet or range "*" for internet egress.
func IsEgressRoutingPolicyAllowedForNodes ¶ added in v1.6.0
IsEgressRoutingPolicyAllowedForNodes reports whether `policy` permits a peering relationship (and corresponding mesh peer ACL rule) between `node` and `peer` on either side of an egress<->egress flow. WireGuard peering is inherently bidirectional: even a Uni "src-egress -> dst-egress" policy requires the src-router and dst-router hosts to complete a wg handshake so the tunnel can carry the one-way L4 traffic. The L4 direction (Uni vs Bi) is then enforced downstream by the FORWARD/INPUT rule generators, not at peer-allow time. We therefore accept the policy whenever EITHER side of the pair routes the matching egress, otherwise the dst-side router would never add the src-side router as a peer (callers query symmetrically as (X, Y) and (Y, X)) and the handshake would silently never occur.
func IsEndpointDetectionEnabled ¶ added in v0.99.0
IsEndpointDetectionEnabled - returns true if endpoint detection enabled
func IsFQDN ¶ added in v1.1.0
IsFQDN checks if the given string is a valid Fully Qualified Domain Name (FQDN)
func IsInternetGw ¶ added in v0.22.0
IsInternetGw - checks if node is acting as internet gw (legacy flag or internet egress router)
func IsMFAEnforced ¶ added in v1.0.0
IsMFAEnforced returns whether MFA has been enforced.
func IsNetworkCIDRUnique ¶ added in v0.21.2
func IsNetworkNameUnique ¶
IsNetworkNameUnique - checks to see if any other networks have the same name (id)
func IsNodeAllowedToCommunicate ¶ added in v0.26.0
func IsNodeAllowedToCommunicate(ctx context.Context, node, peer models.Node, checkDefaultPolicy bool) (bool, []models.Acl)
IsNodeAllowedToCommunicate - check node is allowed to communicate with the peer // ADD ALLOWED DIRECTION - 0 => node -> peer, 1 => peer-> node,
func IsNodeAllowedToCommunicateWithAllRsrcs ¶ added in v1.1.0
func IsOauthUser ¶ added in v0.25.0
IsOauthUser - returns
func IsSlicesEqual ¶ added in v0.22.0
IsSlicesEqual tells whether a and b contain the same elements. A nil argument is equivalent to an empty slice.
func IsStateValid ¶
IsStateValid - checks if given state is valid or not deletes state after call is made to clean up, should only be called once per sign-in
func IsStunEnabled ¶ added in v0.99.0
IsStunEnabled - returns true if STUN set to on
func IsSyncEnabled ¶ added in v0.99.0
IsSyncEnabled returns whether auth provider sync is enabled.
func IsUserAllowedAccessToExtClient ¶
IsUserAllowedAccessToExtClient - checks if user has permission to access extclient
func IsValidMatchDomain ¶ added in v1.1.0
IsValidMatchDomain reports whether s is a valid "match domain". Rules (simple/ASCII):
- "~." is allowed (match all).
- Optional leading "~" allowed (e.g., "~example.com").
- Optional single trailing "." allowed (FQDN form).
- No wildcards "*", no leading ".", no underscores.
- Labels: letters/digits/hyphen (LDH), 1–63 chars, no leading/trailing hyphen.
- Total length (without trailing dot) ≤ 253.
func IsValidVersion ¶ added in v1.4.0
IsValidVersion returns true if the version string can be parsed as semantic version.
func IsVersionCompatible ¶ added in v0.24.1
IsVersionCompatible checks that the version passed is compabtible (>=) with MinVersion
func JoinDeviceNetwork ¶ added in v1.7.0
func JoinDeviceNetwork(ctx context.Context, user *schema.User, host *schema.Host, networkID string) (models.DeviceJoinResult, error)
JoinDeviceNetwork adds the host to a network on behalf of the user.
func LeaveDeviceNetwork ¶ added in v1.7.0
func LeaveDeviceNetwork(ctx context.Context, user *schema.User, host *schema.Host, networkID string) error
LeaveDeviceNetwork removes the host from a network or cancels a pending approval request.
func ListAclsByNetwork ¶ added in v0.30.0
ListAclsByNetwork lists all acl policies in network
func ListAllByRoutingNodeWithDomain ¶ added in v1.1.0
func ListAllByRoutingNodeWithDomain(egs []schema.Egress, nodeID string) (egWithDomain []models.EgressDomain)
func ListDeviceExitNodes ¶ added in v1.7.0
func ListDeviceExitNodes(ctx context.Context, user *schema.User, host *schema.Host, networkID string) ([]models.DeviceExitNode, error)
ListDeviceExitNodes returns internet-type egresses in the network the user may select, filtered by ACL when the default device policy is disabled.
func ListDevicePolicies ¶ added in v0.99.0
ListDevicePolicies - lists all device policies in a network
func ListEgressAcls ¶ added in v0.99.0
func ListEgressPresets ¶ added in v1.6.0
func ListEgressPresets() []models.EgressPresetApp
ListEgressPresets returns the static egress preset catalog (defensive copy of slice header; entries are values).
func ListExitClientsForRoutingNode ¶ added in v1.7.0
func ListExitClientsForRoutingNode(ctx context.Context, network, routingNodeID string) []models.Node
ListExitClientsForRoutingNode returns mesh nodes using this node as their internet exit, via RelayedIGWClients and/or SelectedInternetEgressID pointing at an egress this node routes.
func ListNodeExitNodes ¶ added in v1.7.0
func ListNodeExitNodes(ctx context.Context, network, nodeID string) ([]models.DeviceExitNode, error)
ListNodeExitNodes returns active internet egresses in the network for admin assignment.
func ListNodesBySelectedInternetEgress ¶ added in v1.7.0
ListNodesBySelectedInternetEgress returns network nodes that have selected the given egress.
func ListUserPolicies ¶ added in v0.26.0
ListUserPolicies - lists all user policies in a network
func ManageZombies ¶
ManageZombies - lists tenants and starts a per-tenant zombie-management worker for each.
func MarkStaleNodesOffline ¶ added in v1.6.0
MarkStaleNodesOffline runs on a ticker and bulk-updates the status of every node whose last_check_in is older than models.LastCheckInThreshold to schema.OfflineSt. Promotion back to OnlineSt happens in mq.HandleHostCheckin when a node recovers; the metrics-driven path in pro/logic refines the status further on the next metrics message.
Intended to be started once from the master pod.
func MigrateAclPolicies ¶ added in v0.30.0
func ModelsEnrollmentKeyFromSchema ¶ added in v1.7.0
func ModelsEnrollmentKeyFromSchema(key schema.EnrollmentKey) models.EnrollmentKey
ModelsEnrollmentKeyFromSchema converts a schema enrollment key to the models type.
func NodeIsInternetEgressRouter ¶ added in v1.7.0
NodeIsInternetEgressRouter reports whether the node is a routing node for any active internet egress.
func NormalizeAndValidateAclEgressIPs ¶ added in v1.6.0
func NormalizeCIDR ¶
NormalizeCIDR - returns the first address of CIDR
func NormalizeEgressReqDomains ¶ added in v1.6.0
NormalizeEgressReqDomains validates each domain entry (FQDN or *.suffix), lowercases, and deduplicates while preserving input order.
func NormalizeEgressType ¶ added in v1.7.0
NormalizeEgressType sets Type from range/domains/preset when empty, and forces internet invariants.
func NormalizeIPOrCIDR ¶ added in v1.6.0
func NormalizeOSName ¶ added in v1.4.0
func NotifyMetricExportIntervalChanged ¶ added in v1.6.0
NotifyMetricExportIntervalChanged signals mq.Keepalive to reset the metrics export ticker for ctx's tenant.
func NthSubnet ¶ added in v1.5.1
NthSubnet calculates the nth subnet of a given prefix length within a pool.
func OSFamily ¶ added in v1.4.0
OSFamily returns a normalized OS family string. Examples: "linux-debian", "linux-redhat", "linux-arch", "linux-other", "windows", "darwin"
func PopulateAclPolicyTagNames ¶ added in v1.5.1
PopulateAclPolicyTagNames resolves human-readable names for ACL policy tags
func PreAuthCheck ¶ added in v1.0.0
func PreAuthCheck(next http.Handler) http.HandlerFunc
func PresetYieldsAWSIPRanges ¶ added in v1.6.0
func PresetYieldsAWSIPRanges(p models.EgressPresetApp) bool
PresetYieldsAWSIPRanges reports whether the preset is backed by AWS ip-ranges.json.
func PruneStaleRelayedClients ¶ added in v1.7.0
PruneStaleRelayedClients drops RelayedNodes / InetNodeReq entries that no longer belong on this gateway (missing nodes, or nodes no longer RelayedBy it) and persists when anything changed. Returns true if pruned.
func RandomString ¶
RandomString - returns a random string in a charset
func RebindInternetEgressClients ¶ added in v1.7.0
RebindInternetEgressClients re-applies exit selection for clients of an internet egress after its routing node set changes (e.g. reassignment to a new node).
func RefreshHostPeerInfoCache ¶ added in v1.5.1
RefreshHostPeerInfoCache - batch pre-computes peer info for all hosts and stores the results in the cache. Returns the fetched hosts and nodes so callers can reuse them without redundant DB queries.
func RegenerateEnrollmentKeyToken ¶ added in v1.6.0
func RegenerateEnrollmentKeyToken(ctx context.Context, keyValue string) (*schema.EnrollmentKey, error)
RegenerateEnrollmentKeyToken replaces the enrollment key value, invalidating any previously issued registration tokens while preserving key configuration.
func RegisterDevice ¶ added in v1.7.0
func RegisterDevice(ctx context.Context, user *schema.User, newHost *schema.Host) (models.RegisterResponse, error)
RegisterDevice registers or updates a host on behalf of an authenticated user (Desktop/netclient JWT flow).
func RelayUpdates ¶
func RelayedAllowedIPs ¶
func RemoveAllFromSlice ¶ added in v1.2.0
func RemoveAllFromSlice[T comparable](s []T, val T) []T
RemoveAllFromSlice removes every occurrence of val from s (stable order).
func RemoveHost ¶
RemoveHost - removes a given host from server
func RemoveNodeFromAclPolicy ¶ added in v0.90.0
func RemoveNodeFromAllGatewayRelays ¶ added in v1.7.0
RemoveNodeFromAllGatewayRelays removes nodeID from RelayedClients / RelayedIGWClients on every node in the network. Used on delete so orphan map keys cannot linger.
func RemoveNodeFromEgress ¶ added in v0.99.0
func RemoveNodeFromEnrollmentKeys ¶ added in v1.5.1
func RemoveStringSlice ¶
RemoveStringSlice - removes an element at given index i from a given string slice
func RemoveTagFromEnrollmentKeys ¶ added in v0.26.0
func RequiresProEgressType ¶ added in v1.6.0
RequiresProEgressType reports whether the egress uses domain-based or preset app routing.
func ResetHook ¶ added in v1.4.0
func ResetHook(hookID string)
ResetHook - resets the timer for a hook with the given ID
func ResolveAWSEgressPresetCIDRs ¶ added in v1.6.0
ResolveAWSEgressPresetCIDRs fetches public AWS CIDR data for a supported AWS preset.
func ResolveInheritedAuth ¶ added in v1.7.0
func ResolveInternetExitRoutingNode ¶ added in v1.7.0
ResolveInternetExitRoutingNode sets node.InternetGwID in-memory from SelectedInternetEgressID for peer-update helpers that still read InternetGwID. Does not persist. When the selected egress is unavailable, clears InternetGwID so fail-open is consistent.
func RestartHook ¶ added in v1.4.0
RestartHook - restarts a hook with the given ID (stops and starts again with same configuration) If newInterval is 0, uses the existing interval. Otherwise, uses the new interval.
func RetrievePrivateTrafficKey ¶
RetrievePrivateTrafficKey retrieves private key of server
func RetrievePublicTrafficKey ¶
RetrievePublicTrafficKey retrieves public key of server
func ReturnAcceptedResponse ¶ added in v1.5.1
func ReturnAcceptedResponse(response http.ResponseWriter, request *http.Request, message string)
ReturnAcceptedResponse - returns 202 Accepted for async operations
func ReturnErrorResponse ¶
func ReturnErrorResponse(response http.ResponseWriter, request *http.Request, errorMessage models.ErrorResponse)
ReturnErrorResponse - processes error and adds header
func ReturnErrorResponseWithJson ¶ added in v1.4.0
func ReturnErrorResponseWithJson(response http.ResponseWriter, request *http.Request, msg interface{}, errorMessage models.ErrorResponse)
ReturnErrorResponseWithJson - processes error with body and adds header
func ReturnSuccessResponse ¶
func ReturnSuccessResponse(response http.ResponseWriter, request *http.Request, message string)
ReturnSuccessResponse - processes message and adds header
func ReturnSuccessResponseWithJson ¶ added in v0.22.0
func ReturnSuccessResponseWithJson(response http.ResponseWriter, request *http.Request, res interface{}, message string)
ReturnSuccessResponseWithJson - processes message and adds header
func SanitizeRelayedNodesForUpdate ¶ added in v1.7.0
func SanitizeRelayedNodesForUpdate(gatewayID string, requested []string, priorMapKeys map[string]struct{}) []string
SanitizeRelayedNodesForUpdate drops missing / orphan RelayedNodes IDs from a gateway update payload while still allowing genuinely new assignments (node exists, RelayedBy empty, and ID was not already a stale map key).
func SaveExtClient ¶
SaveExtClient - saves an ext client to database
func SchemaEnrollmentKeyFromModels ¶ added in v1.7.0
func SchemaEnrollmentKeyFromModels(key models.EnrollmentKey) *schema.EnrollmentKey
SchemaEnrollmentKeyFromModels converts a models enrollment key to the schema type.
func SecurityCheck ¶
func SecurityCheck(reqAdmin bool, next http.Handler) http.HandlerFunc
SecurityCheck - Check if user has appropriate permissions
func SelectDeviceExitNode ¶ added in v1.7.0
func SelectDeviceExitNode(ctx context.Context, user *schema.User, host *schema.Host, networkID, egressID string, useTcpUplink bool) (*models.DeviceExitNode, error)
SelectDeviceExitNode sets or clears the selected internet egress for the device's node on the network. useTcpUplink opts into TCP uplink when the exit routing gateway has TCP proxy enabled.
func SetDNSOnWgConfig ¶ added in v1.1.0
func SetDefaultGw ¶ added in v0.23.0
func SetDefaultGw(node models.Node, peerUpdate models.HostPeerUpdate) models.HostPeerUpdate
func SetEgressDomainAnsForDomain ¶ added in v1.6.0
SetEgressDomainAnsForDomain sets resolved CIDRs for a single domain.
func SetEgressDomainAnsForDomains ¶ added in v1.6.0
SetEgressDomainAnsForDomains assigns the same resolved CIDRs to each domain (e.g. static presets).
func SetInternetGw ¶ added in v0.22.0
func SetInternetGw(node *models.Node, req models.InetNodeReq)
SetInternetGw - sets the node as internet gw based on flag bool
func SetNetworkNodesLastModified ¶
SetNetworkNodesLastModified - sets the network nodes last modified
func SetNodeSelectedInternetEgress ¶ added in v1.7.0
SetNodeSelectedInternetEgress sets or clears the node's selected internet egress. Selecting an exit also relays the node through that egress routing node (IsIGWClient), so NAT'd full-tunnel clients remain reachable via the gateway. InternetGwID is not dual-written. useTcpUplink opts the client into TCP uplink when the routing gateway has TCP proxy enabled.
func SetOAuthSecret ¶ added in v1.7.0
func SetRelayedNodes ¶
SetRelayedNodes- sets and saves node as relayed
func SetVerbosity ¶ added in v0.90.0
func SetVerbosity(logLevel int)
func SmtpSkipTlsVerify ¶ added in v1.7.0
func SoleOrganization ¶ added in v1.7.0
func SoleOrganization(ctx context.Context) (*schema.Organization, error)
func SortAclEntrys ¶ added in v0.26.0
SortTagEntrys - Sorts slice of Tag entries by their id
func SortApiHosts ¶
SortApiHosts - Sorts slice of ApiHosts by their ID alphabetically with numbers first
func SortApiNodes ¶
SortApiNodes - Sorts slice of ApiNodes by their ID alphabetically with numbers first
func SortDNSEntrys ¶
SortDNSEntrys - Sorts slice of DNSEnteys by their Address alphabetically with numbers first
func SortExtClient ¶
SortExtClient - Sorts slice of ExtClients by their ClientID alphabetically with numbers first
func SortNetworks ¶
SortNetworks - Sorts slice of Networks by their NetID alphabetically with numbers first
func SortUsers ¶
func SortUsers(unsortedUsers []models.ReturnUser)
SortUsers - Sorts slice of Users by username
func StartCPUProfiling ¶ added in v0.26.0
func StartHookManager ¶
StartHookManager - listens on `HookManagerCh` to run any hook and `HookCommandCh` for commands
func StartMemProfiling ¶ added in v0.30.0
func StartMemProfiling()
func StopCPUProfiling ¶ added in v0.26.0
func StopHook ¶ added in v1.4.0
func StopHook(hookID string)
StopHook - stops a hook with the given ID
func StoreHostPeerUpdate ¶ added in v1.5.1
func StoreHostPeerUpdate(ctx context.Context, hostID string, peerUpdate models.HostPeerUpdate)
StoreHostPeerUpdate - caches a computed HostPeerUpdate for a host. Called as a side-effect of PublishSingleHostPeerUpdate during broadcast.
func StoreJWTSecret ¶
StoreJWTSecret stores server jwt secret if needed
func StringDifference ¶
StringDifference - returns the elements in `a` that aren't in `b`.
func StringSliceContains ¶
StringSliceContains - sees if a string slice contains a string element
func SubscribeMetricExportIntervalReset ¶ added in v1.6.0
SubscribeMetricExportIntervalReset returns a channel notified when the metric interval setting changes for ctx's tenant.
func SyncClearedExitNodeFields ¶ added in v1.7.0
SyncClearedExitNodeFields copies exit/relay fields after ClearExitNodeForDisconnect onto another node object that will be persisted (e.g. the disconnect update payload).
func SyncDevice ¶ added in v1.7.0
SyncDevice requests the host to pull latest config via MQ.
func TimerCheckpoint ¶
func TimerCheckpoint() error
TimerCheckpoint - Checks if 24 hours has passed since telemetry was last sent. If so, sends telemetry data to posthog
func ToReturnUser ¶
func ToReturnUser(user *schema.User) models.ReturnUser
ToReturnUser - gets a user as a return user
func ToUserEventLog ¶ added in v1.5.1
ToUserEventLog - converts a user to an event log entry with resolved group/role names
func ToggleExtClientConnectivity ¶
func ToggleExtClientConnectivity(ctx context.Context, client *models.ExtClient, enable bool) (models.ExtClient, error)
ToggleExtClientConnectivity - enables or disables an ext client
func Tokenize ¶
Tokenize - tokenizes an enrollment key to be used via registration and attaches it to the Token field on the struct
func TransferDeviceHostOwnership ¶ added in v1.7.0
TransferDeviceHostOwnership re-binds a shared desktop host to a new user, cleaning up the prior owner's network state. RegisterDevice does not call this; any API that exposes transfer must enforce admin authorization.
func TryToUseEnrollmentKey ¶
func TryToUseEnrollmentKey(ctx context.Context, k *schema.EnrollmentKey) bool
TryToUseEnrollmentKey - checks first if key can be decremented returns true if it is decremented or isvalid
func UniqueAclPolicyTags ¶ added in v0.99.0
func UniqueAclPolicyTags(tags []models.AclPolicyTag) []models.AclPolicyTag
func UniqueIPNetStrList ¶ added in v0.99.0
UniqueIPNetList deduplicates and sorts a list of CIDR strings.
func UniqueStrings ¶ added in v1.0.0
func UnlinkNetworkAndTagsFromEnrollmentKeys ¶ added in v0.90.0
func UnsetInternetGw ¶ added in v0.23.0
func UpdateEnrollmentKey ¶ added in v0.21.2
func UpdateEnrollmentKey(ctx context.Context, keyValue string, updates *models.APIEnrollmentKey) (*schema.EnrollmentKey, error)
UpdateEnrollmentKey - updates an existing enrollment key's relay and groups
func UpdateExtClient ¶
UpdateExtClient - updates an ext client with new values
func UpdateHost ¶
UpdateHost - updates host data by field
func UpdateHostFromClient ¶
func UpdateHostFromClient(ctx context.Context, newHost, currHost *schema.Host) (isEndpointChanged, sendPeerUpdate bool)
UpdateHostFromClient - used for updating host on server with update recieved from client
func UpdateHostNetwork ¶
UpdateHostNetwork - adds/deletes host from a network
func UpdateHostNode ¶ added in v1.2.0
func UpdateHostNode(ctx context.Context, h *schema.Host, newNode *models.Node) (publishDeletedNodeUpdate, publishPeerUpdate bool, displacedGwNodes []models.Node)
UpdateHostNode - handles updates from client nodes
func UpdateNetwork ¶
UpdateNetwork - updates a network with another network's fields
func UpdateNode ¶
UpdateNode - takes a node and updates another node with it's values
func UpdateNodeCheckin ¶
UpdateNodeCheckin - buffers the checkin timestamp in memory when caching is enabled. The actual DB write is deferred to FlushNodeCheckins (every 30s). When caching is disabled (HA mode), writes directly to the DB.
func UpdateRelayNodes ¶ added in v1.2.0
UpdateRelayNodes - updates relay nodes
func UpdateRelayed ¶
UpdateRelayed - updates a relay's relayed nodes, and sends updates to the relayed nodes over MQ
func UpdateUser ¶
UpdateUser - updates a given user
func UpsertServerSettings ¶ added in v0.99.0
func UpsertServerSettings(ctx context.Context, s models.ServerSettings) error
func UpsertUserSettings ¶ added in v1.1.0
func UpsertUserSettings(username string, userSettings models.UserSettings) error
func UserHasAccessToNetwork ¶ added in v1.7.0
UserHasAccessToNetwork reports whether the given user (with membership fields already loaded) may access/join the network. Prefer this when the caller already fetched the user under the correct tenant scope.
func ValidateAndApproveUserInvite ¶ added in v0.25.0
func ValidateCreateAclReq ¶ added in v0.26.0
ValidateCreateAclReq - validates create req for acl
func ValidateDNSCreate ¶
ValidateDNSCreate - checks if an entry is valid
func ValidateDNSUpdate ¶
ValidateDNSUpdate - validates a DNS update
func ValidateDomain ¶ added in v0.99.0
func ValidateEgressAppNATMode ¶ added in v1.6.0
ValidateEgressAppNATMode rejects virtual NAT for preset-based egress apps.
func ValidateEgressCIDR ¶ added in v1.6.0
ValidateEgressCIDR rejects egress ranges that overlap the Netmaker network or loopback space. Empty range and "*" are allowed (domain-only / inet gw).
func ValidateEgressGateway ¶
func ValidateEgressGateway(gateway models.EgressGatewayRequest) error
ValidateEgressGateway - validates the egress gateway model
func ValidateEgressProOnlyFeatures ¶ added in v1.6.0
ValidateEgressProOnlyFeatures rejects domain and app egress on Community Edition.
func ValidateEgressRange ¶ added in v0.24.3
func ValidateEgressReqProLimits ¶ added in v1.6.0
ValidateEgressReqProLimits rejects domain/app fields on the API request before CE builds an egress.
func ValidateInetGwReq ¶ added in v1.0.0
func ValidateInternetEgressRoutingNode ¶ added in v1.7.0
ValidateInternetEgressRoutingNode ensures a routing node can act as an internet exit node.
func ValidateNetwork ¶
Validate - validates fields of an network struct
func ValidateNewSettings ¶ added in v0.99.0
func ValidateNewSettings(ctx context.Context, req models.ServerSettings) error
func ValidateParams ¶ added in v0.23.0
func ValidateRelay ¶ added in v0.24.0
ValidateRelay - checks if relay is valid
func ValidateUser ¶
ValidateUser - validates a user model
func VerifyAuthRequest ¶
func VerifyAuthRequest(ctx context.Context, authRequest models.UserAuthParams, appName string) (string, error)
VerifyAuthRequest - verifies an auth request
func VerifyDeviceHostAccess ¶ added in v1.7.0
VerifyDeviceHostAccess ensures the user may operate on the given host ID.
func VerifyHostToken ¶
func VerifyHostToken(ctx context.Context, tokenString string) (hostID string, mac string, network string, err error)
VerifyHostToken - [hosts] Only
func VerifyOTPAuthURL ¶ added in v1.0.0
func VerifyUserToken ¶
func VerifyUserToken(ctx context.Context, tokenString string) (username string, issuperadmin, isadmin bool, err error)
VerifyUserToken func will used to Verify the JWT Token while using APIS
func VersionLessThan ¶ added in v0.30.0
VersionLessThan checks if v1 < v2 semantically dev is the latest version
Types ¶
type ApiErrorType ¶ added in v0.99.0
type ApiErrorType string
const ( Internal ApiErrorType = "internal" BadReq ApiErrorType = "badrequest" NotFound ApiErrorType = "notfound" UnAuthorized ApiErrorType = "unauthorized" Forbidden ApiErrorType = "forbidden" )
type CleanupUserRefsFunc ¶ added in v1.7.0
type MetricsMonitor ¶ added in v1.2.0
type MetricsMonitor struct {
// contains filtered or unexported fields
}
func GetMetricsMonitor ¶ added in v1.2.0
func GetMetricsMonitor(ctx context.Context) *MetricsMonitor
func (*MetricsMonitor) Start ¶ added in v1.2.0
func (m *MetricsMonitor) Start()
func (*MetricsMonitor) Stop ¶ added in v1.2.0
func (m *MetricsMonitor) Stop()
type OSInfo ¶ added in v1.4.0
type ServerSyncType ¶ added in v1.5.1
type ServerSyncType string
const ( SyncTypeSettings ServerSyncType = "settings" SyncTypePeerUpdate ServerSyncType = "peer_update" SyncTypeIDPSync ServerSyncType = "idp_sync" SyncTypeIDPReset ServerSyncType = "idp_reset" )
Source Files
¶
- acls.go
- auth.go
- clients.go
- device.go
- device_auth.go
- dns.go
- egress.go
- egress_domain_ans.go
- egress_presets.go
- egress_presets_aws.go
- egress_presets_catalog.go
- enrollmentkey.go
- errors.go
- exit_node.go
- extclient_exit_node.go
- extpeers.go
- gateway.go
- hooks.go
- hosts.go
- jit.go
- jwts.go
- metrics.go
- networks.go
- nodes.go
- peers.go
- proc.go
- relay.go
- scope.go
- security.go
- server.go
- serverconf.go
- settings.go
- status.go
- sysinfo.go
- telemetry.go
- timer.go
- traffic.go
- usage.go
- user_mgmt.go
- users.go
- util.go
- version.go
- wireguard.go
- zombie.go