logic

package
v1.6.0 Latest Latest
Warning

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

Go to latest
Published: Jun 12, 2026 License: Apache-2.0 Imports: 62 Imported by: 6

Documentation

Overview

package for logicing client and server code

Index

Constants

View Source
const (
	DashboardApp       = "dashboard"
	NetclientApp       = "netclient"
	NetmakerDesktopApp = "netmaker-desktop"
)
View Source
const (
	FallbackVNATPool    = "198.18.0.0/15"
	VNATPoolPrefixLen   = 22
	DefaultSitePrefixV4 = 24
	CgnatCIDR           = "100.64.0.0/10"
)
View Source
const (
	MasterUser       = "masteradministrator"
	Forbidden_Msg    = "forbidden"
	Forbidden_Err    = models.Error(Forbidden_Msg)
	Unauthorized_Msg = "unauthorized"
	Unauthorized_Err = models.Error(Unauthorized_Msg)
)
View Source
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
)
View Source
const (
	GooglePublicNameserverName = "Google Public DNS"
)
View Source
const KUBERNETES_LISTEN_PORT = 31821

KUBERNETES_LISTEN_PORT - starting port for Kubernetes in order to use NodePort range

View Source
const KUBERNETES_SERVER_MTU = 1024

KUBERNETES_SERVER_MTU - ideal mtu for kubernetes deployments right now

View Source
const MinVersion = "v0.17.0"
View Source
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

View Source
var (
	CreateDefaultTags = func(netID schema.NetworkID) {}

	DeleteAllNetworkTags = func(networkID schema.NetworkID) {}

	IsUserAllowedToCommunicate = func(userName string, peer models.Node) (bool, []models.Acl) {
		return false, []models.Acl{}
	}

	RemoveUserFromAclPolicy = func(userName string) {}

	EnsureDefaultUserGroupNetworkPolicies = func(old, new *schema.UserGroup) error {
		return nil
	}

	GetGroupNetworksMap = func(group *schema.UserGroup) (map[schema.NetworkID]schema.Network, error) {
		return nil, nil
	}
)
View Source
var (
	IPv4Network = "0.0.0.0/0"
	IPv6Network = "::/0"
)
View Source
var (
	// ErrHostExists error indicating that host exists when trying to create new host
	ErrHostExists error = errors.New("host already exists")
	// ErrInvalidHostID
	ErrInvalidHostID error = errors.New("invalid host id")
)
View Source
var (
	// ResetAutoRelay - function to reset autorelayed peers on this node
	ResetAutoRelay = func(autoRelayNode *models.Node) error {
		return nil
	}
	// ResetAutoRelayedPeer - removes relayed peers for node
	ResetAutoRelayedPeer = func(failedOverNode *models.Node) error {
		return nil
	}
	// GetAutoRelayPeerIps - gets autorelay peerips
	GetAutoRelayPeerIps = func(peer, node *models.Node) []net.IPNet {
		return []net.IPNet{}
	}
	// SetAutoRelay - sets autorelay flag on the node
	SetAutoRelay = func(node *models.Node) {
		node.IsAutoRelay = false
	}
)
View Source
var (
	FreeTier = false
	// DefaultTrialEndDate - is a placeholder date for not applicable trial end dates
	DefaultTrialEndDate, _ = time.Parse("2006-Jan-02", "2021-Apr-01")

	GetTrialEndDate = func() (time.Time, error) {
		return DefaultTrialEndDate, nil
	}
)
View Source
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)")
)
View Source
var AddGlobalGroupOnRoleUpgrade = func(oldRole, newRole schema.UserRoleID, groups map[schema.UserGroupID]struct{}) {
}
View Source
var AddGlobalNetRolesToAdmins = func(u *schema.User) {}
View Source
var AdminPermissionTemplate = schema.UserRole{
	ID:         schema.AdminRole,
	Default:    true,
	FullAccess: true,
}
View Source
var AssignVirtualRangeToEgress = func(nw *schema.Network, eg *schema.Egress) error {
	return nil
}
View Source
var CanUserCreateNetwork = func(ctx context.Context, username string) bool { return true }
View Source
var CheckIfAnyPolicyisUniDirectional = func(targetNode models.Node, acls []models.Acl) bool {
	return false
}
View Source
var CheckJITAccess = func(string, string) (bool, *schema.JITGrant, error) {
	return true, nil, nil
}
View Source
var CheckPostureViolations = func(d models.PostureCheckDeviceInfo, network schema.NetworkID) (v []models.Violation, level schema.Severity) {
	return []models.Violation{}, schema.SeverityUnknown
}
View Source
var CleanupGwsMigration = func() {}
View Source
var CreateDefaultNetworkRolesAndGroups = func(netID schema.NetworkID) {}
View Source
var CreateDefaultUserPolicies = func(netID schema.NetworkID) {
	if netID.String() == "" {
		return
	}
	if !IsAclExists(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(defaultUserAcl)
	}
}
View Source
var DeleteMetrics = func(string) error {
	return nil
}
View Source
var DeleteNetworkRoles = func(netID string) {}
View Source
var DeleteNodeMetricsFromPeers = func(string) {}
View Source
var (
	DeleteNodesCh = make(chan *models.Node, 100)
)
View Source
var DeleteRole = func(r schema.UserRoleID, force bool) error {
	return nil
}
View Source
var EmailInit = func() {}
View Source
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

View Source
var EnterpriseCheckFuncs []func(ctx context.Context, wg *sync.WaitGroup)

EnterpriseCheckFuncs - can be set to run functions for EE

View Source
var ErrEgressProOnlyFeature = errors.New("domain and app egress require Netmaker Pro")

ErrEgressProOnlyFeature is returned when domain or app egress is used on Community Edition.

View Source
var ErrUnknownEgressPreset = errors.New("unknown egress preset_id")

ErrUnknownEgressPreset is returned when preset_id does not match the catalog.

View Source
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.

View Source
var FilterNetworksByRole = func(allnetworks []schema.Network, user *schema.User) []schema.Network {
	return allnetworks
}
View Source
var GetDeploymentMode = func() string {

	return "self-hosted"
}
View Source
var GetEgressUserRulesForNode = func(targetnode *models.Node,
	rules map[string]models.AclRule) map[string]models.AclRule {
	return rules
}
View Source
var GetFeatureFlags = func() models.FeatureFlags {
	return models.FeatureFlags{}
}
View Source
var GetFilteredNodesByUserAccess = func(user *schema.User, nodes []models.Node) (filteredNodes []models.Node) {
	return
}
View Source
var GetFwRulesForNodeAndPeerOnGw = getFwRulesForNodeAndPeerOnGw
View Source
var GetFwRulesForUserNodesOnGw = func(node models.Node, nodes []models.Node) (rules []models.FwRule) { return }
View Source
var GetMetrics = func(string) (*models.Metrics, error) {
	var metrics models.Metrics
	return &metrics, nil
}
View Source
var GetNameserversForHost = getNameserversForHost
View Source
var GetNameserversForNode = getNameserversForNode
View Source
var GetNodeStatus = getNodeCheckInStatus
View Source
var GetPostureCheckDeviceInfoByNode = func(node *models.Node) (d models.PostureCheckDeviceInfo) {
	return
}
View Source
var GetTagMapWithNodesByNetwork = getTagMapWithNodesByNetwork
View Source
var GetUserAclRulesForNode = func(targetnode *models.Node,
	rules map[string]models.AclRule) map[string]models.AclRule {
	return rules
}
View Source
var GetUserGroup = func(groupId schema.UserGroupID) (userGrps schema.UserGroup, err error) { return }
View Source
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",
		},
	},
}
View Source
var GlobalPermissionsCheck = func(username string, r *http.Request) error { return nil }
View Source
var HookCommandCh = make(chan models.HookCommand, 10)

HookCommandCh - channel to send commands to hooks (reset/stop)

View Source
var HookManagerCh = make(chan models.HookDetails, 3)

HookManagerCh - channel to add any new hooks

View Source
var InitialiseRoles = userRolesInit
View Source
var IntialiseGroups = func() {}
View Source
var IsAclPolicyValid = func(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(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(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
}
View Source
var IsGroupsValid = func(groups map[schema.UserGroupID]struct{}) error {
	return nil
}
View Source
var IsOAuthConfigured = func() bool { return false }
View Source
var IsPeerAllowed = func(node, peer models.Node, checkDefaultPolicy bool) bool {
	var nodeId, peerId string

	if node.IsStatic {
		nodeId = node.StaticNode.ClientID
		node = node.StaticNode.ConvertToStaticNode()
	} else {
		nodeId = node.ID.String()
	}
	if peer.IsStatic {
		peerId = peer.StaticNode.ClientID
		peer = peer.StaticNode.ConvertToStaticNode()
	} 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(schema.NetworkID(node.Network), models.DevicePolicy)
		if err == nil {
			if defaultPolicy.Enabled {
				return true
			}
		}

	}

	policies := ListDevicePolicies(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(db.WithContext(context.TODO()))
				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
}
View Source
var LogEvent = func(a *models.Event) {}
View Source
var NetworkHook models.HookFunc = func(params ...interface{}) error {
	networks, err := (&schema.Network{}).ListAll(db.WithContext(context.TODO()))
	if err != nil {
		return err
	}
	allNodes, err := GetAllNodes()
	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(&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(db.WithContext(context.TODO())); err == nil && len(host.Nodes) == 0 {
					(&schema.Host{ID: host.ID}).Delete(db.WithContext(context.TODO()))
				}
			}
		}
	}
	return nil
}
View Source
var NetworkPermissionsCheck = func(username string, r *http.Request) error { return nil }
View Source
var PlatformRoleRequiresGroupEnforcement = func(role schema.UserRoleID) bool { return false }
View Source
var PublishServerSync func(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).

View Source
var ResetAuthProvider = func() {}
View Source
var ResetIDPSyncHook = func() {}
View Source
var ServerSettingsDBKey = "server_cfg"
View Source
var SetPeerMetricsDisconnected = func(string) {}
View Source
var SettingsMutex = &sync.RWMutex{}
View Source
var StartFlowCleanupLoop = func() {}
View Source
var StopFlowCleanupLoop = func() {}
View Source
var StripGroupsOnRoleDowngrade = func(oldRole, newRole schema.UserRoleID, groups map[schema.UserGroupID]struct{}) {
}
View Source
var SuperAdminPermissionTemplate = schema.UserRole{
	ID:         schema.SuperAdminRole,
	Default:    true,
	FullAccess: true,
}

Pre-Define Permission Templates for default Roles

View Source
var SyncFromIDP = func() error { return nil }
View Source
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.

View Source
var UpdateMetrics = func(string, *models.Metrics) error {
	return nil
}
View Source
var UpdateUserGwAccess = func(currentUser, changeUser *schema.User) {}
View Source
var UserHasGlobalNetworksAdminMembership = func(user *schema.User) bool { return false }
View Source
var UserHasNetworkGroupAccess = func(user *schema.User, networkID string) bool { return false }
View Source
var ValidateEgressReq = validateEgressReq
View Source
var ValidateNameserverReq = validateNameserverReq

Functions

func AddEgressInfoToPeerByAccess added in v0.99.0

func AddEgressInfoToPeerByAccess(node, targetNode *models.Node, eli []schema.Egress, acls []models.Acl, isDefaultPolicyActive bool)

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 AddStaticNodestoList(nodes []models.Node) []models.Node

func AddStatusToNodes added in v0.30.0

func AddStatusToNodes(nodes []models.Node, statusCall bool) (nodesWithStatus []models.Node)

func AllDomainAnsFromEgress added in v1.6.0

func AllDomainAnsFromEgress(e schema.Egress) []string

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

func AllocateUniqueVNATPool(network *schema.Network) error

AllocateUniqueVNATPool allocates a unique Virtual NAT pool for a network, ensuring it doesn't conflict with pools already assigned to other networks.

func ApplyConfiguredDomainsToEgress added in v1.6.0

func ApplyConfiguredDomainsToEgress(e *schema.Egress, domains []string)

ApplyConfiguredDomainsToEgress sets Domains on the egress record.

func ApplyEgressPresetToEgressReq added in v1.6.0

func ApplyEgressPresetToEgressReq(req *models.EgressReq) error

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 AssignVirtualNATDefaults added in v1.5.1

func AssignVirtualNATDefaults(network *schema.Network, vpnCIDR string)

AssignVirtualNATDefaults determines safe defaults based on VPN CIDR

func AssociateNodeToHost

func AssociateNodeToHost(n *models.Node, h *schema.Host) error

AssociateNodeToHost - associates a node with a host and persists both.

func AutoUpdateEnabled added in v0.99.0

func AutoUpdateEnabled() bool

AutoUpdateEnabled returns a boolean indicating whether netclient auto update is enabled or disabled default is enabled

func CheckEndpoint

func CheckEndpoint(endpoint string) bool

CheckEndpoint - checks if an endpoint is valid

func CheckHostPorts

func CheckHostPorts(h *schema.Host) (changed bool)

CheckHostPort 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

func CheckIfFileExists(filePath string) bool

CheckIfFileExists - checks if file exists or not in the given path

func CheckTagGroupPolicy added in v0.99.0

func CheckTagGroupPolicy(srcMap, dstMap map[string]struct{}, node, peer models.Node,
	nodeTags, peerTags map[models.TagID]struct{}) bool

func CheckZombies

func CheckZombies(_node *schema.Node)

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

func CleanVersion(raw string) string

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

func CleanupOtherExtclients(extclient *models.ExtClient) error

CleanupOtherExtclients cleans up other clients owned by the same use for the same device and network.

func ClearEgressDomainAns added in v1.6.0

func ClearEgressDomainAns(e *schema.Egress)

ClearEgressDomainAns clears per-domain answers.

func CompareIfaceSlices added in v1.1.0

func CompareIfaceSlices(a, b []schema.Iface) bool

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

func ConfiguredDomainsForEgress(e schema.Egress) []string

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 ContainsCIDR(net1, net2 string) bool

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 ConvHostPassToHash

func ConvHostPassToHash(hostPass string) string

ConvHostPassToHash - converts password to md5 hash

func ConvertModelsNodeToSchemaNode added in v1.6.0

func ConvertModelsNodeToSchemaNode(node *models.Node) *schema.Node

func ConvertSchemaNodeToApiNode added in v1.6.0

func ConvertSchemaNodeToApiNode(_node *schema.Node) *models.ApiNode

func ConvertSchemaNodeToModelsNode added in v1.6.0

func ConvertSchemaNodeToModelsNode(_node *schema.Node) *models.Node

func CreateDNS

func CreateDNS(entry models.DNSEntry) (models.DNSEntry, error)

CreateDNS - creates a DNS entry

func CreateDefaultAclNetworkPolicies added in v0.26.0

func CreateDefaultAclNetworkPolicies(netID schema.NetworkID)

CreateDefaultAclNetworkPolicies - create default acl network policies

func CreateEgressGateway

func CreateEgressGateway(gateway models.EgressGatewayRequest) (models.Node, error)

CreateEgressGateway - creates an egress gateway

func CreateEnrollmentKey

func CreateEnrollmentKey(uses int, expiration time.Time, networks,
	tags []string, groups []models.TagID, unlimited bool, relay uuid.UUID,
	defaultKey, autoEgress, autoAssignGw bool) (*models.EnrollmentKey, error)

CreateEnrollmentKey - creates a new enrollment key in db

func CreateFallbackNameserver added in v1.4.0

func CreateFallbackNameserver(networkID string) error

func CreateHost

func CreateHost(h *schema.Host) error

CreateHost - creates a host if not exist

func CreateJWT

func CreateJWT(uuid string, macAddress string, network string) (response string, err error)

CreateJWT func will used to create the JWT while signing in and signing out

func CreateNetwork

func CreateNetwork(_network *schema.Network) error

CreateNetwork - creates a network in database

func CreatePreAuthToken added in v1.0.0

func CreatePreAuthToken(username string) (string, error)

CreatePreAuthToken generate a jwt token to be used as intermediate token after primary-factor authentication but before secondary-factor authentication.

func CreateSuperAdmin

func CreateSuperAdmin(u *schema.User) error

CreateSuperAdmin - creates an super admin user

func CreateUser

func CreateUser(_user *schema.User) error

CreateUser - creates a user

func CreateUserAccessJwtToken added in v0.99.0

func CreateUserAccessJwtToken(username string, role schema.UserRoleID, d time.Time, tokenID string) (response string, err error)

CreateUserJWT - creates a user jwt token

func CreateUserJWT

func CreateUserJWT(username string, role schema.UserRoleID, appName string) (response string, err error)

CreateUserJWT - creates a user jwt token

func DeTokenize

func DeTokenize(b64Token string) (*models.EnrollmentKey, error)

DeTokenize - detokenizes a base64 encoded string and finds the associated enrollment key

func DeleteAcl added in v0.26.0

func DeleteAcl(a models.Acl) error

DeleteAcl - deletes acl policy

func DeleteDNS

func DeleteDNS(domain string, network string) error

DeleteDNS - deletes a DNS entry

func DeleteEgressGateway

func DeleteEgressGateway(network, nodeid string) (models.Node, error)

DeleteEgressGateway - deletes egress from node

func DeleteEnrollmentKey

func DeleteEnrollmentKey(value string, force bool) error

DeleteEnrollmentKey - delete's a given enrollment key by value

func DeleteExpiredNodes

func DeleteExpiredNodes(ctx context.Context)

DeleteExpiredNodes - goroutine which deletes nodes which are expired

func DeleteExtClient

func DeleteExtClient(network string, clientid string, isUpdate bool) error

DeleteExtClient - deletes an existing ext client

func DeleteExtClientAndCleanup added in v0.24.1

func DeleteExtClientAndCleanup(extClient models.ExtClient) error

DeleteExtClientAndCleanup - deletes an existing ext client and update ACLs

func DeleteGatewayExtClients

func DeleteGatewayExtClients(gatewayID string, networkName string) error

DeleteGatewayExtClients - deletes ext clients based on gateway (mac) of ingress node and network

func DeleteIngressGateway

func DeleteIngressGateway(nodeid string) (models.Node, []models.ExtClient, error)

DeleteIngressGateway - deletes an ingress gateway

func DeleteNetwork

func DeleteNetwork(network string, force bool, done chan struct{}) error

DeleteNetwork - deletes a network

func DeleteNetworkDNS added in v1.6.0

func DeleteNetworkDNS(network string) error

func DeleteNetworkPolicies added in v0.90.0

func DeleteNetworkPolicies(netId schema.NetworkID)

DeleteNetworkPolicies - deletes all default network acl policies

func DeleteNode

func DeleteNode(node *models.Node, purge bool) error

func DeleteNodeByID added in v0.21.2

func DeleteNodeByID(node *models.Node) error

DeleteNodeByID - deletes a node from database

func DeletePendingUser added in v0.24.0

func DeletePendingUser(username string) error

func DeleteRelay added in v0.90.0

func DeleteRelay(network, nodeid string) ([]models.Node, models.Node, error)

DeleteRelay - deletes a relay

func DeleteUser

func DeleteUser(user string) error

DeleteUser - deletes a given user

func DeleteUserInvite added in v0.25.0

func DeleteUserInvite(email string) error

func DeleteUserSettings added in v1.1.0

func DeleteUserSettings(userID string) error

func DisassociateAllNodesFromHost

func DisassociateAllNodesFromHost(hostIDStr string) error

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 DisplaceAutoRelayedNodes added in v1.5.1

func DisplaceAutoRelayedNodes(nodeID string) []models.Node

DisplaceAutoRelayedNodes removes auto-assigned nodes from a disconnected gateway and returns the displaced nodes that need re-assignment.

func DissasociateNodeFromHost

func DissasociateNodeFromHost(n *models.Node, h *schema.Host) error

DissasociateNodeFromHost - deletes a node and removes from host nodes should be the only way nodes are deleted as of 0.18

func DoesHostExistInTheNetworkAlready added in v1.6.0

func DoesHostExistInTheNetworkAlready(h *schema.Host, network *schema.Network) bool

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 DoesNodeHaveAccessToEgress(node *models.Node, e *schema.Egress, acls []models.Acl) bool

func DoesUserHaveAccessToEgress added in v1.1.0

func DoesUserHaveAccessToEgress(user *schema.User, e *schema.Egress, acls []models.Acl) bool

func DomainAnsForDomain added in v1.6.0

func DomainAnsForDomain(e schema.Egress, domain string) []string

DomainAnsForDomain returns resolved CIDRs for one configured domain.

func DomainAnsMapFromEgress added in v1.6.0

func DomainAnsMapFromEgress(e schema.Egress) map[string][]string

DomainAnsMapFromEgress returns domain -> resolved CIDRs from domain_ans_by_domain.

func EgressDNs added in v1.1.0

func EgressDNs(network string) (entries []models.DNSEntry)

func EgressDomainsEqual added in v1.6.0

func EgressDomainsEqual(a, b []string) bool

EgressDomainsEqual compares two domain lists as sets (order-independent).

func EnterpriseCheck

func EnterpriseCheck(ctx context.Context, wg *sync.WaitGroup)

EnterpriseCheck - Runs enterprise functions if presented

func FetchAuthSecret

func FetchAuthSecret() (string, error)

FetchAuthSecret - manages secrets for oauth

func FetchJWTSecret

func FetchJWTSecret() (string, error)

FetchJWTSecret - fetches jwt secret from db

func FetchPassValue added in v0.25.0

func FetchPassValue(newValue string) (string, error)

func FetchTelemetryData added in v0.23.0

func FetchTelemetryData() telemetryData

FetchTelemetryData - fetches telemetry data: count of various object types in DB

func FetchTelemetryRecord added in v0.23.0

func FetchTelemetryRecord() (models.Telemetry, error)

FetchTelemetryRecord - get the existing UUID and Timestamp from the DB

func FileExists

func FileExists(f string) bool

FileExists - checks if local file exists

func FilterOutIPs added in v1.2.0

func FilterOutIPs(ips []string, filters map[string]bool) []string

FilterOutIPs removes ips in the filters map from the ips slice.

func FlattenDomainAnsMap added in v1.6.0

func FlattenDomainAnsMap(m map[string][]string) []string

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 GenerateNodeName(network string) (string, error)

func GenerateOTPAuthURLSignature added in v1.0.0

func GenerateOTPAuthURLSignature(url string) string

func GetAcl added in v0.26.0

func GetAcl(aID string) (models.Acl, error)

GetAcl - gets acl info by id

func GetAclRuleForInetGw added in v0.99.0

func GetAclRuleForInetGw(targetnode models.Node) (rules map[string]models.AclRule)

func GetAclRulesForNode added in v0.30.0

func GetAclRulesForNode(targetnodeI *models.Node) (rules map[string]models.AclRule)

func GetAllDNS

func GetAllDNS() ([]models.DNSEntry, error)

GetAllDNS - gets all dns entries

func GetAllEnrollmentKeys

func GetAllEnrollmentKeys() ([]models.EnrollmentKey, error)

GetAllEnrollmentKeys - fetches all enrollment keys from DB

func GetAllExtClients

func GetAllExtClients() ([]models.ExtClient, error)

GetAllExtClients - gets all ext clients from DB

func GetAllExtClientsWithStatus added in v0.99.0

func GetAllExtClientsWithStatus(status schema.NodeStatus) ([]models.ExtClient, error)

GetAllExtClientsWithStatus - returns all external clients with given status.

func GetAllHostsAPI

func GetAllHostsAPI(hosts []schema.Host) []models.ApiHost

GetAllHostsAPI - get's all the hosts in an API usable format

func GetAllHostsWithStatus added in v0.99.0

func GetAllHostsWithStatus(status schema.NodeStatus) ([]schema.Host, error)

GetAllHostsWithStatus - returns all hosts with at least one node with given status.

func GetAllNodes

func GetAllNodes() ([]models.Node, error)

GetAllNodes - returns all nodes in the DB

func GetAllNodesAPI

func GetAllNodesAPI(nodes []models.Node) []models.ApiNode

GetAllNodesAPI - get all nodes for api usage

func GetAllNodesAPIWithLocation added in v1.0.0

func GetAllNodesAPIWithLocation(nodes []models.Node) []models.ApiNode

GetAllNodesAPI - get all nodes for api usage

func GetAllRsrcIDForRsrc added in v1.1.0

func GetAllRsrcIDForRsrc(rsrc schema.RsrcType) schema.RsrcID

func GetAllowedEmailDomains added in v0.99.0

func GetAllowedEmailDomains() string

GetAllowedEmailDomains - gets the allowed email domains for oauth signup

func GetAllowedIPs

func GetAllowedIPs(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

func GetAllowedIpForInetNodeClient(node, peer *models.Node) []net.IPNet

GetAllowedIpForInetNodeClient - get inet cidr for node using a inet gw

func GetAllowedIpsForRelayed

func GetAllowedIpsForRelayed(relayed, relay *models.Node) (allowedIPs []net.IPNet)

GetAllowedIpsForRelayed - returns the peerConfig for a node relayed by relay

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

func GetAzureTenant() string

GetAzureTenant - retrieve the azure tenant ID from env variable or config file

func GetCachedHostPeerUpdate added in v1.5.1

func GetCachedHostPeerUpdate(hostID string) (models.HostPeerUpdate, bool)

GetCachedHostPeerUpdate - returns a cached HostPeerUpdate if available.

func GetClientIP added in v1.0.0

func GetClientIP(r *http.Request) string

func GetCurrentServerUsage added in v1.2.0

func GetCurrentServerUsage() (limits models.Usage)

func GetCustomDNS

func GetCustomDNS(network string) ([]models.DNSEntry, error)

GetCustomDNS - gets the custom DNS of a network

func GetDNS

func GetDNS(network string) ([]models.DNSEntry, error)

GetDNS - gets the DNS of a current network

func GetDNSEntryNum

func GetDNSEntryNum(domain string, network string) (int, error)

GetDNSEntryNum - gets which entry the dns was

func GetDefaultDomain added in v0.99.0

func GetDefaultDomain() string

GetDefaultDomain - get the default domain

func GetDefaultEnrollmentKeyForNetwork added in v1.6.0

func GetDefaultEnrollmentKeyForNetwork(network string) (models.EnrollmentKey, error)

GetDefaultEnrollmentKeyForNetwork returns the default enrollment key for a network.

func GetDefaultHosts

func GetDefaultHosts() []schema.Host

GetDefaultHosts - retrieve all hosts marked as default from DB

func GetDefaultPolicy added in v0.26.0

func GetDefaultPolicy(netID schema.NetworkID, ruleType models.AclPolicyType) (models.Acl, error)

GetDefaultPolicy - fetches default policy in the network by ruleType

func GetEgressDefaultAllowAllFwRule added in v1.6.0

func GetEgressDefaultAllowAllFwRule(node models.Node) (models.AclRule, bool)

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 GetEgressDomainNSForNode(node *models.Node) (returnNsLi []models.Nameserver)

func GetEgressDomainsByAccessForUser added in v1.4.0

func GetEgressDomainsByAccessForUser(user *schema.User, network schema.NetworkID) (domains []string)

func GetEgressIPs

func GetEgressIPs(peer *models.Node) []net.IPNet

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 GetEgressRanges(netID schema.NetworkID) (map[string][]string, map[string]struct{}, error)

func GetEgressRangesOnNetwork

func GetEgressRangesOnNetwork(client *models.ExtClient) ([]string, error)

ExtClient.GetEgressRangesOnNetwork - returns the egress ranges on network of ext client

func GetEgressRulesForNode added in v0.90.0

func GetEgressRulesForNode(targetnode models.Node) (rules map[string]models.AclRule)

func GetEmaiSenderPassword added in v0.99.0

func GetEmaiSenderPassword() string

func GetEnrollmentKey

func GetEnrollmentKey(value string) (key models.EnrollmentKey, err error)

GetEnrollmentKey - fetches a single enrollment key returns nil and error if not found

func GetExtClient

func GetExtClient(clientid string, network string) (models.ExtClient, error)

GetExtClient - gets a single ext client on a network

func GetExtClientByName

func GetExtClientByName(ID string) (models.ExtClient, error)

GetExtClientByName - gets an ext client by name

func GetExtClientsByID

func GetExtClientsByID(nodeid, network string) ([]models.ExtClient, error)

GetExtClientsByID - gets the clients of attached gateway

func GetExtPeers added in v0.24.2

func GetExtPeers(node, peer *models.Node, addressIdentityMap map[string]models.PeerIdentity) ([]wgtypes.PeerConfig, []models.IDandAddr, []models.EgressNetworkRoutes, error)

func GetExtclientAllowedIPs added in v0.22.0

func GetExtclientAllowedIPs(client models.ExtClient) (allowedIPs []string)

func GetExtclientDNS added in v0.22.0

func GetExtclientDNS() []models.DNSEntry

GetExtclientDNS - gets all extclients dns entries

func GetFwRulesOnIngressGateway added in v0.26.0

func GetFwRulesOnIngressGateway(node models.Node) (rules []models.FwRule)

func GetGwDNS added in v1.1.0

func GetGwDNS(node *models.Node) string

func GetHostByNodeID

func GetHostByNodeID(id string) *schema.Host

GetHostByNodeID - returns a host if found to have a node's ID, else nil

func GetHostNetworks

func GetHostNetworks(hostID string) []string

GetHostNetworks - fetches all the networks

func GetHostNodes

func GetHostNodes(host *schema.Host) []models.Node

GetHostNodes - fetches all nodes part of the host

func GetHostPeerInfo added in v0.90.0

func GetHostPeerInfo(host *schema.Host) (models.HostPeerInfo, error)

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

func GetIDPSyncInterval() time.Duration

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 GetJwtValidityDuration added in v0.99.0

func GetJwtValidityDuration() time.Duration

GetJwtValidityDuration - returns the JWT validity duration in minutes

func GetJwtValidityDurationForClients added in v1.1.0

func GetJwtValidityDurationForClients() time.Duration

GetJwtValidityDurationForClients returns the JWT validity duration in minutes for clients.

func GetManageDNS added in v0.99.0

func GetManageDNS() bool

GetManageDNS - if manage DNS enabled or not

func GetMetricInterval added in v0.99.0

func GetMetricInterval() string

GetMetricInterval - get the publish metric interval

func GetMetricIntervalInMinutes added in v0.99.0

func GetMetricIntervalInMinutes() time.Duration

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

func GetMetricsPort() int

GetMetricsPort - get metrics port

func GetNetworkExtClients

func GetNetworkExtClients(network string) ([]models.ExtClient, error)

GetNetworkExtClients - gets the ext clients of given network

func GetNetworkNetworkCIDR4 added in v1.5.1

func GetNetworkNetworkCIDR4(network *schema.Network) *net.IPNet

func GetNetworkNetworkCIDR6 added in v1.5.1

func GetNetworkNetworkCIDR6(network *schema.Network) *net.IPNet

func GetNetworkNodes

func GetNetworkNodes(network string) ([]models.Node, error)

GetNetworkNodes - gets the nodes of a network

func GetNetworkNodesMemory

func GetNetworkNodesMemory(allNodes []models.Node, network string) []models.Node

GetNetworkNodesMemory - gets all nodes belonging to a network from list in memory

func GetNetworkNonServerNodeCount

func GetNetworkNonServerNodeCount(networkName string) (int, error)

GetNetworkNonServerNodeCount - get number of network non server nodes

func GetNodeByHostRef added in v0.21.2

func GetNodeByHostRef(hostid, network string) (node models.Node, err error)

GetNodeByHostRef - gets the node by host id and network

func GetNodeByID

func GetNodeByID(nodeID string) (models.Node, error)

func GetNodeCheckInStatus added in v0.90.0

func GetNodeCheckInStatus(node *schema.Node) schema.NodeStatus

func GetNodeDNS

func GetNodeDNS(network string) ([]models.DNSEntry, error)

GetNodeDNS - gets the DNS of a network node

func GetNodeEgressInfo added in v0.99.0

func GetNodeEgressInfo(targetNode *models.Node, eli []schema.Egress, acls []models.Acl)

func GetNodesByIDs added in v1.6.0

func GetNodesByIDs(ids []string) (map[string]models.Node, error)

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

func GetOnboardingStatus(ctx context.Context, username string) (models.OnboardingStatus, error)

GetOnboardingStatus reports whether the UI should show the first-network onboarding flow.

func GetPeerListenPort

func GetPeerListenPort(host *schema.Host) int

GetPeerListenPort - given a host, retrieve it's appropriate listening port

func GetPeerUpdateForHost

func GetPeerUpdateForHost(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

func GetRacRestrictToSingleNetwork() bool

GetRacRestrictToSingleNetwork - returns whether the feature to allow simultaneous network connections via RAC is enabled

func GetRecordKey

func GetRecordKey(id string, network string) (string, error)

GetRecordKey - get record key depricated

func GetRelatedHosts

func GetRelatedHosts(hostID string) []schema.Host

GetRelatedHosts - fetches related hosts of a given host

func GetReturnUser

func GetReturnUser(username string) (models.ReturnUser, error)

GetReturnUser - gets a user

func GetRunningHooks added in v1.4.0

func GetRunningHooks() []string

GetRunningHooks - returns a list of currently running hook IDs

func GetSenderEmail added in v0.99.0

func GetSenderEmail() string

func GetSenderUser added in v0.99.0

func GetSenderUser() string

func GetServerConfig added in v0.99.0

func GetServerConfig() config.ServerConfig

GetServerConfig - gets the server config into memory from file or env

func GetServerInfo added in v0.99.0

func GetServerInfo() models.ServerConfig

GetServerInfo - gets the server config into memory from file or env

func GetServerSettings added in v0.99.0

func GetServerSettings() (s models.ServerSettings)

func GetServerSettingsFromEnv added in v0.99.0

func GetServerSettingsFromEnv() (s models.ServerSettings)

func GetSmtpHost added in v0.99.0

func GetSmtpHost() string

func GetSmtpPort added in v0.99.0

func GetSmtpPort() int

func GetState

func GetState(state string) (*models.SsoState, error)

GetState - gets an SsoState from DB, if expired returns error

func GetStaticNodeIps added in v0.26.0

func GetStaticNodeIps(node models.Node) (ips []net.IP)

func GetStaticNodesByNetwork added in v0.26.0

func GetStaticNodesByNetwork(network schema.NetworkID, onlyWg bool) (staticNode []models.Node)

func GetStunServers added in v0.99.0

func GetStunServers() string

func GetSuperAdmin

func GetSuperAdmin() (models.ReturnUser, error)

GetSuperAdmin - fetches superadmin user

func GetUserInvite added in v0.25.0

func GetUserInvite(email string) (*schema.UserInvite, error)

func GetUserMap added in v0.25.0

func GetUserMap() (map[string]schema.User, error)

func GetUserNameFromToken added in v0.25.0

func GetUserNameFromToken(authtoken string) (username string, err error)

func GetUserSettings added in v1.1.0

func GetUserSettings(userID string) models.UserSettings

func GetUsers

func GetUsers() ([]models.ReturnUser, error)

GetUsers - gets users

func GetVerbosity added in v0.99.0

func GetVerbosity() int32

func HasEgressDomainAns added in v1.6.0

func HasEgressDomainAns(e schema.Egress) bool

HasEgressDomainAns is true when at least one resolved CIDR exists for any domain.

func HasSuperAdmin

func HasSuperAdmin() (bool, error)

HasSuperAdmin - checks if server has an superadmin/owner

func HostExists

func HostExists(h *schema.Host) bool

HostExists - checks if given host already exists

func IfaceDelta

func IfaceDelta(currentNode *models.Node, newNode *models.Node) bool

IfaceDelta - checks if the new node causes an interface change

func InitNetworkHooks added in v1.4.0

func InitNetworkHooks()

func InitializeZombies

func InitializeZombies()

InitializeZombies - populates the zombie quarantine list (should be called from initialization)

func InsertAcl added in v0.26.0

func InsertAcl(a models.Acl) error

InsertAcl - creates acl policy

func InvalidateHostPeerCaches added in v1.5.1

func InvalidateHostPeerCaches()

InvalidateHostPeerCaches clears both hostPeerInfoCache and hostPeerUpdateCache so they are rebuilt on next access or refresh.

func InvalidateServerSettingsCache added in v1.5.1

func InvalidateServerSettingsCache()

InvalidateServerSettingsCache clears the in-memory settings cache so the next GetServerSettings call re-reads from the database.

func IsAWSEgressPreset added in v1.6.0

func IsAWSEgressPreset(presetID string) bool

IsAWSEgressPreset reports whether presetID refers to an AWS catalog entry.

func IsAclExists added in v0.26.0

func IsAclExists(aclID string) bool

IsAclExists - checks if acl exists

func IsAddressInCIDR

func IsAddressInCIDR(address net.IP, cidr string) bool

IsAddressInCIDR - util to see if an address is in a cidr or not

func IsBase64

func IsBase64(s string) bool

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

func IsBasicAuthEnabled() bool

IsBasicAuthEnabled - checks if basic auth has been configured to be turned off

func IsDNSEntryValid added in v0.30.0

func IsDNSEntryValid(d string) bool

IsNetworkNameValid - checks if a netid of a network uses valid characters

func IsDomainBasedEgress added in v1.6.0

func IsDomainBasedEgress(e schema.Egress) bool

IsDomainBasedEgress is true when this egress has at least one configured logical domain.

func IsEgressAppEgress added in v1.6.0

func IsEgressAppEgress(e schema.Egress) bool

IsEgressAppEgress reports whether the egress was created from a catalog preset (egress app).

func IsEgressDomainPattern added in v1.6.0

func IsEgressDomainPattern(domain string) bool

IsEgressDomainPattern returns true for a normal FQDN or a single-label wildcard prefix form (*.example.com).

func IsEgressInternetGateway added in v1.6.0

func IsEgressInternetGateway(e schema.Egress) bool

IsEgressInternetGateway is true when range is "*" (full internet egress).

func IsEgressReqInternetGateway added in v1.6.0

func IsEgressReqInternetGateway(req *models.EgressReq) bool

IsEgressReqInternetGateway is true when the request uses range "*" for internet egress.

func IsEgressRoutingPolicyAllowedForNodes added in v1.6.0

func IsEgressRoutingPolicyAllowedForNodes(policy models.Acl, node, peer models.Node) bool

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

func IsEndpointDetectionEnabled() bool

IsEndpointDetectionEnabled - returns true if endpoint detection enabled

func IsFQDN added in v1.1.0

func IsFQDN(domain string) bool

IsFQDN checks if the given string is a valid Fully Qualified Domain Name (FQDN)

func IsInternetGw added in v0.22.0

func IsInternetGw(node models.Node) bool

IsInternetGw - checks if node is acting as internet gw

func IsMFAEnforced added in v1.0.0

func IsMFAEnforced() bool

IsMFAEnforced returns whether MFA has been enforced.

func IsNetworkCIDRUnique added in v0.21.2

func IsNetworkCIDRUnique(cidr4 *net.IPNet, cidr6 *net.IPNet) bool

func IsNetworkNameUnique

func IsNetworkNameUnique(network *schema.Network) (bool, error)

IsNetworkNameUnique - checks to see if any other networks have the same name (id)

func IsNodeAllowedToCommunicate added in v0.26.0

func IsNodeAllowedToCommunicate(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 IsNodeAllowedToCommunicateWithAllRsrcs(node models.Node) bool

func IsOauthUser added in v0.25.0

func IsOauthUser(user *schema.User) error

IsOauthUser - returns

func IsPendingUser added in v0.24.0

func IsPendingUser(username string) bool

func IsSlicesEqual added in v0.22.0

func IsSlicesEqual(a, b []string) bool

IsSlicesEqual tells whether a and b contain the same elements. A nil argument is equivalent to an empty slice.

func IsStateValid

func IsStateValid(state string) (string, bool)

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

func IsStunEnabled() bool

IsStunEnabled - returns true if STUN set to on

func IsSyncEnabled added in v0.99.0

func IsSyncEnabled() bool

IsSyncEnabled returns whether auth provider sync is enabled.

func IsUserAllowedAccessToExtClient

func IsUserAllowedAccessToExtClient(username string, client models.ExtClient) bool

IsUserAllowedAccessToExtClient - checks if user has permission to access extclient

func IsValidMatchDomain added in v1.1.0

func IsValidMatchDomain(s string) bool

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

func IsValidVersion(raw string) bool

IsValidVersion returns true if the version string can be parsed as semantic version.

func IsVersionCompatible added in v0.24.1

func IsVersionCompatible(ver string) bool

IsVersionCompatible checks that the version passed is compabtible (>=) with MinVersion

func ListAcls added in v0.26.0

func ListAcls() (acls []models.Acl)

func ListAclsByNetwork added in v0.30.0

func ListAclsByNetwork(netID schema.NetworkID) ([]models.Acl, error)

ListAcls - lists all acl policies

func ListAllByRoutingNodeWithDomain added in v1.1.0

func ListAllByRoutingNodeWithDomain(egs []schema.Egress, nodeID string) (egWithDomain []models.EgressDomain)

func ListDevicePolicies added in v0.99.0

func ListDevicePolicies(netID schema.NetworkID) []models.Acl

ListDevicePolicies - lists all device policies in a network

func ListEgressAcls added in v0.99.0

func ListEgressAcls(eID string) ([]models.Acl, error)

ListEgressAcls - list egress acl policies

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 ListUserPolicies added in v0.26.0

func ListUserPolicies(netID schema.NetworkID) []models.Acl

ListUserPolicies - lists all user policies in a network

func ManageZombies

func ManageZombies(ctx context.Context)

ManageZombies - goroutine which adds/removes/deletes nodes from the zombie node quarantine list

func MarkStaleNodesOffline added in v1.6.0

func MarkStaleNodesOffline(ctx context.Context)

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 Mask added in v0.99.0

func Mask() string

func MigrateAclPolicies added in v0.30.0

func MigrateAclPolicies()

func NetworkExists

func NetworkExists(name string) (bool, error)

NetworkExists - check if network exists

func NormalizeAndValidateAclEgressIPs added in v1.6.0

func NormalizeAndValidateAclEgressIPs(acl *models.Acl) error

func NormalizeCIDR

func NormalizeCIDR(address string) (string, error)

NormalizeCIDR - returns the first address of CIDR

func NormalizeEgressReqDomains added in v1.6.0

func NormalizeEgressReqDomains(domains []string) ([]string, error)

NormalizeEgressReqDomains validates each domain entry (FQDN or *.suffix), lowercases, and deduplicates while preserving input order.

func NormalizeIPOrCIDR added in v1.6.0

func NormalizeIPOrCIDR(value string) (string, error)

func NormalizeOSName added in v1.4.0

func NormalizeOSName(raw string) string

func NotifyMetricExportIntervalChanged added in v1.6.0

func NotifyMetricExportIntervalChanged()

NotifyMetricExportIntervalChanged signals mq.Keepalive to reset the metrics export ticker.

func NthSubnet added in v1.5.1

func NthSubnet(pool *net.IPNet, newPrefixLen int, n int) *net.IPNet

NthSubnet calculates the nth subnet of a given prefix length within a pool.

func OSFamily added in v1.4.0

func OSFamily(osName string) string

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

func PopulateAclPolicyTagNames(acls []models.Acl)

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 RandomString

func RandomString(length int) string

RandomString - returns a random string in a charset

func RefreshHostPeerInfoCache added in v1.5.1

func RefreshHostPeerInfoCache() ([]schema.Host, []models.Node)

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(keyID string) (*models.EnrollmentKey, error)

RegenerateEnrollmentKeyToken replaces the enrollment key value, invalidating any previously issued registration tokens while preserving key configuration.

func RelayUpdates

func RelayUpdates(currentNode, newNode *models.Node) bool

func RelayedAllowedIPs

func RelayedAllowedIPs(peer, node *models.Node) []net.IPNet

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

func RemoveHost(h *schema.Host, forceDelete bool) error

RemoveHost - removes a given host from server

func RemoveNodeFromAclPolicy added in v0.90.0

func RemoveNodeFromAclPolicy(node models.Node)

func RemoveNodeFromEgress added in v0.99.0

func RemoveNodeFromEgress(node models.Node)

func RemoveNodeFromEnrollmentKeys added in v1.5.1

func RemoveNodeFromEnrollmentKeys(node *models.Node)

func RemoveStringSlice

func RemoveStringSlice(slice []string, i int) []string

RemoveStringSlice - removes an element at given index i from a given string slice

func RemoveTagFromEnrollmentKeys added in v0.26.0

func RemoveTagFromEnrollmentKeys(deletedTagID models.TagID)

func RequiresProEgressType added in v1.6.0

func RequiresProEgressType(e schema.Egress) bool

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

func ResolveAWSEgressPresetCIDRs(client *http.Client, p models.EgressPresetApp) ([]string, error)

ResolveAWSEgressPresetCIDRs fetches public AWS CIDR data for a supported AWS preset.

func RestartHook added in v1.4.0

func RestartHook(hookID string, newInterval time.Duration)

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

func RetrievePrivateTrafficKey() ([]byte, error)

RetrievePrivateTrafficKey - retrieves private key of server

func RetrievePublicTrafficKey

func RetrievePublicTrafficKey() ([]byte, error)

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 SaveExtClient

func SaveExtClient(extclient *models.ExtClient) error

SaveExtClient - saves an ext client to database

func SaveNetwork

func SaveNetwork(_network *schema.Network) error

SaveNetwork - save network struct to database

func SecurityCheck

func SecurityCheck(reqAdmin bool, next http.Handler) http.HandlerFunc

SecurityCheck - Check if user has appropriate permissions

func SetAuthSecret added in v0.24.0

func SetAuthSecret(secret string) error

func SetCorefile

func SetCorefile(domains string) error

SetCorefile - sets the core file of the system

func SetDNSOnWgConfig added in v1.1.0

func SetDNSOnWgConfig(gwNode *models.Node, extclient *models.ExtClient)

func SetDefaultGw added in v0.23.0

func SetDefaultGw(node models.Node, peerUpdate models.HostPeerUpdate) models.HostPeerUpdate

func SetDefaultGwForRelayedUpdate added in v0.23.0

func SetDefaultGwForRelayedUpdate(relayed, relay models.Node, peerUpdate models.HostPeerUpdate) models.HostPeerUpdate

func SetEgressDomainAnsForDomain added in v1.6.0

func SetEgressDomainAnsForDomain(e *schema.Egress, domain string, ans []string)

SetEgressDomainAnsForDomain sets resolved CIDRs for a single domain.

func SetEgressDomainAnsForDomains added in v1.6.0

func SetEgressDomainAnsForDomains(e *schema.Egress, domains, ans []string)

SetEgressDomainAnsForDomains assigns the same resolved CIDRs to each domain (e.g. static presets).

func SetFreeTierForTelemetry

func SetFreeTierForTelemetry(freeTierFlag bool)

setFreeTierForTelemetry - store free tier flag without having an import cycle when used for telemetry (as the pro package needs the logic package as currently written).

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 SetJWTSecret

func SetJWTSecret()

SetJWTSecret - sets the jwt secret on server startup

func SetNetworkNodesLastModified

func SetNetworkNodesLastModified(networkName string) error

SetNetworkNodesLastModified - sets the network nodes last modified

func SetRelayedNodes

func SetRelayedNodes(setRelayed bool, relay string, relayed []string) []models.Node

SetRelayedNodes- sets and saves node as relayed

func SetState

func SetState(appName, state string) error

SetState - sets a state with new expiration

func SetUserDefaults

func SetUserDefaults(user *schema.User)

SetUserDefaults - sets the defaults of a user to avoid empty fields

func SetVerbosity added in v0.90.0

func SetVerbosity(logLevel int)

func SortAclEntrys added in v0.26.0

func SortAclEntrys(acls []models.Acl)

SortTagEntrys - Sorts slice of Tag entries by their id

func SortApiHosts

func SortApiHosts(unsortedHosts []models.ApiHost)

SortApiHosts - Sorts slice of ApiHosts by their ID alphabetically with numbers first

func SortApiNodes

func SortApiNodes(unsortedNodes []models.ApiNode)

SortApiNodes - Sorts slice of ApiNodes by their ID alphabetically with numbers first

func SortDNSEntrys

func SortDNSEntrys(unsortedDNSEntrys []models.DNSEntry)

SortDNSEntrys - Sorts slice of DNSEnteys by their Address alphabetically with numbers first

func SortExtClient

func SortExtClient(unsortedExtClient []models.ExtClient)

SortExtClient - Sorts slice of ExtClients by their ClientID alphabetically with numbers first

func SortNetworks

func SortNetworks(unsortedNetworks []schema.Network)

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 StartCPUProfiling() *os.File

func StartHookManager

func StartHookManager(ctx context.Context, wg *sync.WaitGroup)

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 StopCPUProfiling(f *os.File)

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(hostID string, peerUpdate models.HostPeerUpdate)

StoreHostPeerUpdate - caches a computed HostPeerUpdate for a host. Called as a side-effect of PublishSingleHostPeerUpdate during broadcast.

func StoreJWTSecret

func StoreJWTSecret(privateKey string) error

StoreJWTSecret - stores server jwt secret if needed

func StringDifference

func StringDifference(a, b []string) []string

StringDifference - returns the elements in `a` that aren't in `b`.

func StringSliceContains

func StringSliceContains(slice []string, item string) bool

StringSliceContains - sees if a string slice contains a string element

func SubscribeMetricExportIntervalReset added in v1.6.0

func SubscribeMetricExportIntervalReset() <-chan struct{}

SubscribeMetricExportIntervalReset returns a channel notified when the metric interval setting changes.

func Telemetry added in v0.99.0

func Telemetry() string

Telemetry - checks if telemetry data should be sent

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

func ToUserEventLog(user *schema.User) models.UserEventLog

ToUserEventLog - converts a user to an event log entry with resolved group/role names

func ToggleExtClientConnectivity

func ToggleExtClientConnectivity(client *models.ExtClient, enable bool) (models.ExtClient, error)

ToggleExtClientConnectivity - enables or disables an ext client

func Tokenize

func Tokenize(k *models.EnrollmentKey, serverAddr string) error

Tokenize - tokenizes an enrollment key to be used via registration and attaches it to the Token field on the struct

func TryToUseEnrollmentKey

func TryToUseEnrollmentKey(k *models.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 UniqueIPNetList added in v0.90.0

func UniqueIPNetList(ipnets []net.IPNet) []net.IPNet

func UniqueIPNetStrList added in v0.99.0

func UniqueIPNetStrList(ipnets []string) []string

UniqueIPNetList deduplicates and sorts a list of CIDR strings.

func UniquePolicies added in v0.99.0

func UniquePolicies(items []models.Acl) []models.Acl

func UniqueStrings added in v1.0.0

func UniqueStrings(input []string) []string

func UnlinkNetworkAndTagsFromEnrollmentKeys added in v0.90.0

func UnlinkNetworkAndTagsFromEnrollmentKeys(network string, delete bool) error

func UnsetInternetGw added in v0.23.0

func UnsetInternetGw(node *models.Node)

func UpdateAcl added in v0.26.0

func UpdateAcl(newAcl, acl models.Acl) error

UpdateAcl - updates allowed fields on acls and commits to DB

func UpdateEnrollmentKey added in v0.21.2

func UpdateEnrollmentKey(keyId string, updates *models.APIEnrollmentKey) (*models.EnrollmentKey, error)

UpdateEnrollmentKey - updates an existing enrollment key's associated relay

func UpdateExtClient

func UpdateExtClient(old *models.ExtClient, update *models.CustomExtClient) models.ExtClient

UpdateExtClient - updates an ext client with new values

func UpdateHost

func UpdateHost(newHost, currentHost *schema.Host)

UpdateHost - updates host data by field

func UpdateHostFromClient

func UpdateHostFromClient(newHost, currHost *schema.Host) (isEndpointChanged, sendPeerUpdate bool)

UpdateHostFromClient - used for updating host on server with update recieved from client

func UpdateHostNetwork

func UpdateHostNetwork(h *schema.Host, network string, add bool) (*models.Node, error)

UpdateHostNetwork - adds/deletes host from a network

func UpdateHostNode added in v1.2.0

func UpdateHostNode(h *schema.Host, newNode *models.Node) (publishDeletedNodeUpdate, publishPeerUpdate bool, displacedGwNodes []models.Node)

UpdateHostNode - handles updates from client nodes

func UpdateNetwork

func UpdateNetwork(currentNetwork, newNetwork *schema.Network) error

UpdateNetwork - updates a network with another network's fields

func UpdateNode

func UpdateNode(currentNode *models.Node, newNode *models.Node) error

UpdateNode - takes a node and updates another node with it's values

func UpdateNodeCheckin

func UpdateNodeCheckin(nodeID string) error

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

func UpdateRelayNodes(relay string, oldNodes []string, newNodes []string) []models.Node

UpdateRelayNodes - updates relay nodes

func UpdateRelayed

func UpdateRelayed(currentNode, newNode *models.Node)

UpdateRelayed - updates a relay's relayed nodes, and sends updates to the relayed nodes over MQ

func UpdateUser

func UpdateUser(userchange, _user *schema.User) (*schema.User, error)

UpdateUser - updates a given user

func UpsertAcl added in v0.26.0

func UpsertAcl(acl models.Acl) error

UpsertAcl - upserts acl

func UpsertHost

func UpsertHost(h *schema.Host) error

UpsertHost - upserts into DB a given host model, does not check for existence*

func UpsertNetwork added in v1.1.0

func UpsertNetwork(_network *schema.Network) error

func UpsertNode

func UpsertNode(newNode *models.Node) error

UpsertNode - updates node in the DB

func UpsertServerSettings added in v0.99.0

func UpsertServerSettings(s models.ServerSettings) error

func UpsertUser

func UpsertUser(_user schema.User) error

UpsertUser - updates user in the db

func UpsertUserSettings added in v1.1.0

func UpsertUserSettings(userID string, userSettings models.UserSettings) error

func UserPermissions

func UserPermissions(reqAdmin bool, token string) (string, error)

UserPermissions - checks token stuff

func ValidateAndApproveUserInvite added in v0.25.0

func ValidateAndApproveUserInvite(email, code string) error

func ValidateCreateAclReq added in v0.26.0

func ValidateCreateAclReq(req models.Acl) error

ValidateCreateAclReq - validates create req for acl

func ValidateDNSCreate

func ValidateDNSCreate(entry models.DNSEntry) error

ValidateDNSCreate - checks if an entry is valid

func ValidateDNSUpdate

func ValidateDNSUpdate(change models.DNSEntry, entry models.DNSEntry) error

ValidateDNSUpdate - validates a DNS update

func ValidateDomain added in v0.99.0

func ValidateDomain(domain string) bool

func ValidateEgressAppNATMode added in v1.6.0

func ValidateEgressAppNATMode(e schema.Egress) error

ValidateEgressAppNATMode rejects virtual NAT for preset-based egress apps.

func ValidateEgressCIDR added in v1.6.0

func ValidateEgressCIDR(network *schema.Network, cidr string) error

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

func ValidateEgressProOnlyFeatures(e schema.Egress) error

ValidateEgressProOnlyFeatures rejects domain and app egress on Community Edition.

func ValidateEgressRange added in v0.24.3

func ValidateEgressRange(netID string, ranges []string) error

func ValidateEgressReqProLimits added in v1.6.0

func ValidateEgressReqProLimits(req *models.EgressReq) error

ValidateEgressReqProLimits rejects domain/app fields on the API request before CE builds an egress.

func ValidateInetGwReq added in v1.0.0

func ValidateInetGwReq(node *schema.Node, req models.InetNodeReq, update bool) error

func ValidateNetwork

func ValidateNetwork(network *schema.Network, isUpdate bool) error

Validate - validates fields of an network struct

func ValidateNewSettings added in v0.99.0

func ValidateNewSettings(req models.ServerSettings) error

func ValidateParams added in v0.23.0

func ValidateParams(nodeid, netid string) (models.Node, error)

func ValidateRelay added in v0.24.0

func ValidateRelay(relay models.RelayRequest, update bool) error

ValidateRelay - checks if relay is valid

func ValidateUser

func ValidateUser(user *schema.User) error

ValidateUser - validates a user model

func VerifyAuthRequest

func VerifyAuthRequest(authRequest models.UserAuthParams, appName string) (string, error)

VerifyAuthRequest - verifies an auth request

func VerifyHostToken

func VerifyHostToken(tokenString string) (hostID string, mac string, network string, err error)

VerifyHostToken - [hosts] Only

func VerifyOTPAuthURL added in v1.0.0

func VerifyOTPAuthURL(url, signature string) bool

func VerifyUserToken

func VerifyUserToken(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

func VersionLessThan(v1, v2 string) (bool, error)

VersionLessThan checks if v1 < v2 semantically dev is the latest version

func WrapHook added in v1.4.0

func WrapHook(hook func() error) models.HookFunc

WrapHook - wraps a parameterless hook function to be compatible with HookFunc This allows backward compatibility with existing hooks that don't accept parameters

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 GlobalNs added in v1.1.0

type GlobalNs struct {
	ID  string   `json:"id"`
	IPs []string `json:"ips"`
}

type MetricsMonitor added in v1.2.0

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

func GetMetricsMonitor added in v1.2.0

func GetMetricsMonitor() *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 OSInfo struct {
	OS            string `json:"os"`             // e.g. "ubuntu", "windows", "macos"
	OSFamily      string `json:"os_family"`      // e.g. "linux-debian", "windows"
	OSVersion     string `json:"os_version"`     // e.g. "22.04", "10.0.22631"
	KernelVersion string `json:"kernel_version"` // e.g. "6.8.0"
}

func GetOSInfo added in v1.4.0

func GetOSInfo() OSInfo

GetOSInfo returns OS, OSFamily, OSVersion and KernelVersion for the current platform.

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

Directories

Path Synopsis
pro

Jump to

Keyboard shortcuts

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