Files
340ae1521f NM-295: publish TCP uplink flags and peer tcp_proxy_endpoint (#4106)
* wip(go): use default jwt for org tokens;

* wip(go): detach request context from goroutine context;

* wip(go): allow single tenant creation;

* wip(go): remove debug logs;

* wip(go): derive host tenant id from enrollment key tenant id;

* wip(go): skip server settings migration for new deployment;

* wip(go): return auth token with user on create org owner;

* wip(go): prevent use of default tenant slug ;

* wip(go): upsert settings for tenant in ctx;

* wip(go): use passed ctx when updating user; remove password validation from ValidateUser (already validated in UpdateUser);

* wip(go): qualify all tenant id usages with table name;

* wip(go): use passed ctx

* wip(go): return old enrollment key type on create;

* wip(go): prevent null networks return;

* wip(go): wire ctx in dns/nameserver functions; wire ctx in host registration functions;

* wip(go): wire ctx in node functions;

* wip(go): wire ctx in node functions;

* wip(go): wire ctx in extclient functions;

* wip(go): remove not needed field;

* wip(go): use passed ctx;

* wip(go): use unique index instead of primary key;

* wip(go): wire ctx in extclient apis;

* wip(go): wire ctx in extclient apis;

* wip(go): remove org id check from global scoped get tenant api;

* wip(go): add scope slug to discover response;

* wip(go): wire ctx in get users;

* wip(go): set tenant id in posture check violations;

* wip(go): upsert membership instead of user;

* wip(go): pass correct len;

* wip(go): optimize (single loop);

* wip(go): unify todos;

* wip(go): add todo;

* wip(go): wire context for network get;

* wip(go): wire context;

* wip(go): wire context;

* wip(go): wire ctx when getting tenant superadmin;

* wip(go): add network creator to network admin group;

* wip(go): check for user membership on sync;

* wip(go): add methods with strict membership check;

* wip(go): remove unwanted feature flags;

* wip(go): report per-tenant usage during license validation;

* wip(go): move email setting from tenant to org;

* wip(go): pass org scope to email init;

* wip(go): remove old tenant email settings usages; use org settings to get email settings

* wip(go): use get email settings from org settings;

* wip(go): remove email settings migration;

* wip(go): migrate email settings from server to org settings;

* wip(go): assign global network admin group membership only for super-admin and admins;

* wip(go): assign global network admin group membership only for super-admin and admins;

* wip(go): add membership alias to filter;

* wip(go): skip clearing local license validation response cache;

* wip(go): extend license validation response for multi-tenancy;

* wip(go): add functions to get sole tenant and org;

* wip(go): use tenant-specific feature flags;

* wip(go): add tenant status type;

* wip(go): remove old hook comment;

* wip(go): expect ctx during license validation;

* wip(go): always create default org and tenant for ce;

* wip(go): add tenant-specific check for license validation error;

* wip(go): cache license validation response in memory;

* wip(go): add todo to handle multiple-tenant for integration pull;

* wip(go): pass ctx during license validation;

* wip(go): add todo for making changes later; run hook separately for each tenant;

* wip(go): return specific errors when license validation response not in cache;

* wip(go): use retryable.httpclient for calling license validation api;

* wip(go): process license validation;

* wip(go): license validation function;

* wip(go): migration on license validation;

* wip(go): org settings not expected;

* wip(go): remove expiry from license validation response;

* wip(go): add limits and limits enforcement to license validation response;

* wip(go): remove expiry usages;

* wip(go): add arg to clear cache;

* wip(go): add arg to clear cache;

* wip(go): skip license validation if cached resp;

* wip(go): allow org_id and tenant_id query params;

* wip(go): upsert tenant membership on sync;

* wip(go): pass ctx to delete network roles;

* wip(go): create tenant membership on org owner creation on ce;

* wip(go): add tenant orchestrator;

* wip(go): use tenant orchestrator;

* wip(go): add default settings for tenant;

* wip(go): make org owner superadmin on all tenants;

* wip(go): simplify SyncOrgAndTenants;

* wip(go): retry license validation only 3 times

* wip(go): store invalid err;

* wip(go): add function to check if limits are to be enforced on a tenant;

* wip(go): pass tenant scope if possible when checking for license validation error;

* wip(go): remove merge errors;

* wip(go): add functions for limit checks;

* wip(go): wire host limit check;

* wip(go): wire ingress limit check;

* wip(go): wire egress limit check;

* wip(go): wire client limit check;

* wip(go): wire network limit check;

* wip(go): wire user limit check;

* wip(go): use correct errors;

* wip(go): skip telemetry for msps;

* wip(go): disable telemetry on msp tenants;

* wip(go): err check;

* wip(go): uncomment log event;

* wip(go): get sso state to get scope for non-headless oauth login;

* wip(go): inline delete pending user;

* wip(go): allow both org and tenant scope for pending users table;

* wip(go): add migration for pending user table during set tenant id and rekey org/tenant id;

* wip(go): update queries to use new scope fields in pending users table;

* wip(go): allow both org and tenant scope for user invites table;

* wip(go): update queries to use new scope fields;

* wip(go): add migration for rekey-ing org/tenant id and setting tenant id;

* wip(go): inline delete user invite;

* wip(go): set scope when creating invite;

* wip(go): get user count with membership is ctx is tenant scoped;

* wip(go): add methods to upsert and delete org memberships;

* wip(go): add global valid tenant and org roles map;

* wip(go): add scope query in user invite get by email;

* wip(go): add support for upsert and delete of org and tenant membership both;

* wip(go): infer scope for user invite apis;

* wip(go): wire ctx in get user invite by email;

* wip(go): allow no scope headers to be passed in infer scope apis;

* wip(go): add validation and checks for org-scoped invite api handlers;

* wip(go): wire ctx to is pending user check;

* wip(go): infer scope for pending user apis;

* wip(go): set default role based on ctx scope;

* wip(go): move mfa to tenant membership table; move account status to membership tables;

* wip(go): migrate account status and mfa settings;

* wip(go): update account status on sync;

* wip(go): use update mfa to update mfa setting;

* wip(go): set new membership settings on user creation;

* wip(go): use membership where required;

* wip(go): wire ctx on key unlink refs;

* wip(go): use r.Context directly without reinitializing db;

* wip(go): wire ctx in acls;

* wip(go): add tenant scoped primary key constructor;

* wip(go): use tenant scoped primary key for acls, dns, extclients and tags;

* wip(go): wire ctx for get groups in network;

* wip(go): wire ctx for get groups;

* wip(go): scope non-uuid group ids by tenant id;

* wip(go): migrate non-uuid group ids to scoped ids;

* wip(go): don't expect scope id in invite validation and signup apis;

* wip(go): wire ctx for get matching user; allow org scope when querying by external idp id;

* wip(go): add mfa to org;

* wip(go): scope preauth token;

* wip(go): add fallback for older auth tokens;

* wip(go): wire ctx for preauth token creation;

* wip(go): migrate mfa settings;

* wip(go): resolve mfa settings for inherited auth;

* wip(go): update mfa for org;

* wip(go): infer scope for totp apis;

* wip(go): use ctx when passed;

* wip(go): infer scope for list user apis;

* wip(go): ensure set primary keys don't cause errors during fetch;

* wip(go): make primary key for integrations uuid and store provider in separate key;

* wip(go): migrate integration ids;

* wip(go): use provider instead of id everywhere;

* wip(go): remove gorm column;

* wip(go): wire ctx for igw egress creation;

* wip(go): wire ctx for igw egress update;

* wip(go): wire ctx for host registration;

* wip(go): wire ctx for host registration;

* wip(go): merge errors;

* wip(go): merge errors;

* wip(go): wire ctx; remove default scope usages;

* wip(go): use get with membership;

* wip(go): org scope license validation;

* wip(go): remove debug log;

* wip(go): remove scoping on list roles;

* wip(go): ignore invite creation if already exists;

* wip(go): add is msp func to check if deployment is msp deployment;

* wip(go): ensure username is email for msp users;

* wip(go): add email validated check on user table;

* wip(go): mark email validated when oauth user;

* wip(go): handle gorm error;

* wip(go): add tenant id to siem grpc schema;

* wip(go): read tenant from scoped ctx;

* wip(go): pass scoped ctx to siem grpc client;

* wip(go): remove unused publisher;

* wip(go): publish all tenant exporter updates on pull;

* wip(go): fix wg usage;

* wip(go): tenant scope the ctx when getting server info;

* NM-295: publish TCP uplink flags and peer tcp_proxy_endpoint

Add gateway tcp_proxy_enabled/listen port and client use_tcp_uplink,
and populate PeerIDs on host-level pulls so clients receive dial targets.

* wip(go): add tenant id to enrollment key token;

* wip(go): make host register tenant scope;

* wip(go): add default settings;

* wip(go): use correct checks for is msp tenant;

* wip(go): add email validation extension;

* wip(go): add pages for validation check;

* wip(go): use extension for validating user;

* wip(go): add invite type;

* wip(go): create only one validation invite per user email;

* wip(go): add validate email handler;

* wip(go): add email builder;

* wip(go): add user invite type migration logic;

* wip(go): only log email send failures;

* wip(go): add tenant id to flows table;

* wip(go): add func to check if connected to clickhouse;

* wip(go): migrate clickhouse;

* wip(go): add tenant id to mdm and edr state;

* wip(go): add delete methods for tables;

* wip(go): add tenant teardown method;

* wip(go): handle tenant deletion;

* wip(go): clean up flow logs on tenant deletion;

* wip(go): add update org membership role id method;

* wip(go): add transfer org ownership api;

* wip(go): move audit logs retention period to org settings;

* wip(go):get retention period from org settings;

* wip(go): remove old audit logs usage;

* wip(go): migrate audit logs retention period;

* wip(go): unmarshal decodes nums as float64;

* wip(go): run flow logs cleanup for all tenants in one go;

* wip(go): add audit logs retention period and smtp settings to tenant settings table for non-msp tenants;

* wip(go): resolve retention period and smtp settings correctly;

* wip(go): handle retention period and smtp settings updates and fetches correctly;

* wip(go): overlay retention period and smtp settings on server settings;;

* wip(go): upsert overlayed settings;

* NM-295: resolve pr comments

* wip(go): add azure tenant id to org settings;

* wip(go): tenant scope list roles;

* wip(go): add noop creds;

* wip(go): use first instead of find;

* NM-295: check network hook cleanup time

* wip(go): use correct roles when transfering ownership;

* wip(go): delete access tokens only if tenant scoped;

* wip(go): make delete user work for both org and tenant scope;

* wip(go): delete extclients only if tenant scoped;

* wip(go): check if caller is allowed to delete user;

* wip(go): infer scope for update user;

* wip(go): prevent org-owner elevation;

* wip(go): permissions check for update;

* wip(go): delete user access tokens only if tenant scope;

* wip(go): delete extclients only if tenant scope;

* wip(go): move upsert membership in upsert user;

* wip(go): set api host when constructing server config;

* NM-295: mv proxy settings to host

* NM-295: preserve tcp uplink setting on disconnect/connect

* NM-295: show tcpuplink option on exit node gw if enabled

* NM-295: fix orphan gateway relayed client nodes

---------

Co-authored-by: VishalDalwadi <[email protected]>
Co-authored-by: Vishal Dalwadi <[email protected]>
2026-08-18 16:17:30 +05:30

597 lines
17 KiB
Go

package logic
import (
"context"
"crypto/sha1"
"encoding/binary"
"errors"
"fmt"
"math/big"
"net"
"sort"
"strings"
"time"
"github.com/gravitl/netmaker/db"
"github.com/gravitl/netmaker/models"
"github.com/gravitl/netmaker/schema"
"github.com/gravitl/netmaker/scope"
"gorm.io/gorm"
)
var ErrNetworkLimitExceeded = errors.New("network limit reached for this tenant, please upgrade your license")
var NetworkLimitExceeded = func(ctx context.Context) bool {
return false
}
// DeleteNetwork - deletes a network
func DeleteNetwork(ctx context.Context, network string, force bool, done chan struct{}) error {
defer func(ctx context.Context) {
// Delete default network enrollment key
keys, _ := GetAllEnrollmentKeys(ctx)
for _, key := range keys {
if key.Default && enrollmentKeyAppliesToNetwork(key, network) {
_ = DeleteEnrollmentKey(ctx, key.Value, true)
break
}
}
_ = DeleteNetworkDNS(ctx, network)
}(scope.WithContext(db.WithContext(context.Background()), scope.Level(ctx), scope.ID(ctx)))
nodeCount, err := GetNetworkNonServerNodeCount(ctx, network)
if nodeCount == 0 || errors.Is(err, gorm.ErrRecordNotFound) {
_network := &schema.Network{
Name: network,
}
// delete server nodes first then db records
return _network.Delete(ctx)
}
// Remove All Nodes
go func(ctx context.Context) {
nodes, err := GetNetworkNodes(ctx, network)
if err == nil {
for _, node := range nodes {
node := node
host := &schema.Host{ID: node.HostID}
if err := host.Get(ctx); err != nil {
continue
}
if node.IsGw {
// delete ext clients belonging to gateway
DeleteGatewayExtClients(ctx, node.ID.String(), node.Network)
}
DisassociateNodeFromHost(ctx, &node, host)
}
}
// delete server nodes first then db records
_network := &schema.Network{
Name: network,
}
err = _network.Delete(ctx)
if err != nil {
return
}
done <- struct{}{}
close(done)
}(scope.WithContext(db.WithContext(context.Background()), scope.Level(ctx), scope.ID(ctx)))
return nil
}
// AssignVirtualNATDefaults determines safe defaults based on VPN CIDR
func AssignVirtualNATDefaults(network *schema.Network, vpnCIDR string) {
const (
cgnatCIDR = "100.64.0.0/10"
fallbackIPv4Pool = "198.18.0.0/15"
defaultIPv4SitePrefix = 24
)
// Parse CGNAT CIDR (should always succeed, but check for safety)
_, cgnatNet, err := net.ParseCIDR(cgnatCIDR)
if err != nil {
// Fallback to default pool if CGNAT parsing fails (shouldn't happen)
network.VirtualNATPoolIPv4 = fallbackIPv4Pool
network.VirtualNATSitePrefixLenIPv4 = defaultIPv4SitePrefix
return
}
var virtualIPv4Pool string
// Parse VPN CIDR - if it fails or is empty, use fallback
if vpnCIDR == "" {
virtualIPv4Pool = fallbackIPv4Pool
} else {
_, vpnNet, err := net.ParseCIDR(vpnCIDR)
if err != nil || vpnNet == nil {
// Invalid VPN CIDR, use fallback
virtualIPv4Pool = fallbackIPv4Pool
} else if !cidrOverlaps(vpnNet, cgnatNet) {
// Safe to reuse VPN CIDR for Virtual NAT
virtualIPv4Pool = vpnCIDR
} else {
// VPN is CGNAT — must not reuse
virtualIPv4Pool = fallbackIPv4Pool
}
}
network.VirtualNATPoolIPv4 = virtualIPv4Pool
network.VirtualNATSitePrefixLenIPv4 = defaultIPv4SitePrefix
}
// cidrOverlaps checks if two CIDR blocks overlap
func cidrOverlaps(a, b *net.IPNet) bool {
return a.Contains(b.IP) || b.Contains(a.IP)
}
const (
FallbackVNATPool = "198.18.0.0/15"
VNATPoolPrefixLen = 22
DefaultSitePrefixV4 = 24
CgnatCIDR = "100.64.0.0/10"
)
// AllocateUniqueVNATPool allocates a unique Virtual NAT pool for a network,
// ensuring it doesn't conflict with pools already assigned to other networks.
func AllocateUniqueVNATPool(ctx context.Context, network *schema.Network) error {
networks, err := (&schema.Network{}).ListAll(ctx)
if err != nil {
return fmt.Errorf("failed to list networks: %w", err)
}
allocatedPools := make(map[string]struct{})
for _, n := range networks {
if n.VirtualNATSitePrefixLenIPv4 > 0 {
if _, _, err := net.ParseCIDR(n.VirtualNATPoolIPv4); err == nil {
allocatedPools[n.VirtualNATPoolIPv4] = struct{}{}
}
}
}
_, cgnatNet, err := net.ParseCIDR(CgnatCIDR)
if err != nil {
return fmt.Errorf("failed to parse CGNAT CIDR: %w", err)
}
_, fallbackNet, err := net.ParseCIDR(FallbackVNATPool)
if err != nil {
return fmt.Errorf("failed to parse fallback pool: %w", err)
}
vpnCIDR := network.AddressRange
needsUniquePool := false
if vpnCIDR == "" {
needsUniquePool = true
} else {
_, vpnNet, err := net.ParseCIDR(vpnCIDR)
if err != nil || vpnNet == nil {
needsUniquePool = true
} else if cidrOverlaps(vpnNet, cgnatNet) {
needsUniquePool = true
}
}
if needsUniquePool {
uniquePool := AllocateUniquePoolFromFallback(fallbackNet, VNATPoolPrefixLen, allocatedPools, network.Name)
if uniquePool == "" {
return fmt.Errorf("failed to allocate unique Virtual NAT pool for network %s: pool exhausted", network.Name)
}
network.VirtualNATPoolIPv4 = uniquePool
network.VirtualNATSitePrefixLenIPv4 = DefaultSitePrefixV4
} else {
AssignVirtualNATDefaults(network, vpnCIDR)
}
return nil
}
// AllocateUniquePoolFromFallback allocates a unique subnet of the given prefix length
// from the fallback pool, skipping any subnets already present in the allocated map.
func AllocateUniquePoolFromFallback(pool *net.IPNet, newPrefixLen int, allocated map[string]struct{}, seed string) string {
if pool == nil {
return ""
}
poolPrefixLen, bits := pool.Mask.Size()
if newPrefixLen < poolPrefixLen || newPrefixLen > bits {
return ""
}
total := 1 << uint(newPrefixLen-poolPrefixLen)
start := vnatHashIndex(seed, total)
for i := 0; i < total; i++ {
idx := (start + i) % total
cand := NthSubnet(pool, newPrefixLen, idx)
if cand == nil || cand.IP == nil {
continue
}
cs := cand.String()
if _, _, err := net.ParseCIDR(cs); err != nil {
continue
}
if _, used := allocated[cs]; !used {
return cs
}
}
return ""
}
// NthSubnet calculates the nth subnet of a given prefix length within a pool.
func NthSubnet(pool *net.IPNet, newPrefixLen int, n int) *net.IPNet {
if pool == nil {
return nil
}
poolPrefixLen, bits := pool.Mask.Size()
if newPrefixLen < poolPrefixLen || newPrefixLen > bits || n < 0 {
return nil
}
base := ipToBigInt(pool.IP)
size := new(big.Int).Lsh(big.NewInt(1), uint(bits-newPrefixLen))
offset := new(big.Int).Mul(big.NewInt(int64(n)), size)
ipInt := new(big.Int).Add(base, offset)
ip := bigIntToIP(ipInt, bits)
mask := net.CIDRMask(newPrefixLen, bits)
return &net.IPNet{IP: ip.Mask(mask), Mask: mask}
}
func ipToBigInt(ip net.IP) *big.Int {
if v4 := ip.To4(); v4 != nil {
return new(big.Int).SetBytes(v4)
}
if v6 := ip.To16(); v6 != nil {
return new(big.Int).SetBytes(v6)
}
return big.NewInt(0)
}
func bigIntToIP(i *big.Int, bits int) net.IP {
b := i.Bytes()
byteLen := bits / 8
if len(b) < byteLen {
pad := make([]byte, byteLen-len(b))
b = append(pad, b...)
}
ip := net.IP(b)
if bits == 32 {
return ip.To4()
}
return ip
}
func vnatHashIndex(seed string, mod int) int {
if mod <= 1 {
return 0
}
sum := sha1.Sum([]byte(seed))
v := binary.BigEndian.Uint32(sum[:4])
return int(v % uint32(mod))
}
// GetOnboardingStatus reports whether the UI should show the first-network onboarding flow.
func GetOnboardingStatus(ctx context.Context, username string) (models.OnboardingStatus, error) {
networks, err := (&schema.Network{}).ListAll(ctx)
if err != nil {
return models.OnboardingStatus{}, err
}
count := len(networks)
return models.OnboardingStatus{
ShowOnboarding: count == 0 && CanUserCreateNetwork(ctx, username),
NetworkCount: count,
}, nil
}
// CreateNetwork - creates a network in database
func CreateNetwork(ctx context.Context, _network *schema.Network) error {
if _network.AddressRange != "" {
normalizedRange, err := NormalizeCIDR(_network.AddressRange)
if err != nil {
return err
}
_network.AddressRange = normalizedRange
}
if _network.AddressRange6 != "" {
normalizedRange, err := NormalizeCIDR(_network.AddressRange6)
if err != nil {
return err
}
_network.AddressRange6 = normalizedRange
}
if !IsNetworkCIDRUnique(ctx, GetNetworkNetworkCIDR4(_network), GetNetworkNetworkCIDR6(_network)) {
return errors.New("network cidr already in use")
}
_network.NodesUpdatedAt = time.Now().UTC()
err := ValidateNetwork(ctx, _network, false)
if err != nil {
//logic.ReturnErrorResponse(w, r, logic.FormatError(err, "badrequest"))
return err
}
if NetworkLimitExceeded(ctx) {
return ErrNetworkLimitExceeded
}
return _network.Create(ctx)
}
func GetNetworkNetworkCIDR4(network *schema.Network) *net.IPNet {
if network.AddressRange == "" {
return nil
}
_, netCidr, _ := net.ParseCIDR(network.AddressRange)
return netCidr
}
func GetNetworkNetworkCIDR6(network *schema.Network) *net.IPNet {
if network.AddressRange6 == "" {
return nil
}
_, netCidr, _ := net.ParseCIDR(network.AddressRange6)
return netCidr
}
// GetNetworkNonServerNodeCount - get number of network non server nodes
func GetNetworkNonServerNodeCount(ctx context.Context, networkName string) (int, error) {
nodes, err := GetNetworkNodes(ctx, networkName)
return len(nodes), err
}
func IsNetworkCIDRUnique(ctx context.Context, cidr4 *net.IPNet, cidr6 *net.IPNet) bool {
networks, err := (&schema.Network{}).ListAll(ctx)
if err != nil {
return errors.Is(err, gorm.ErrRecordNotFound)
}
for _, network := range networks {
if intersect(GetNetworkNetworkCIDR4(&network), cidr4) ||
intersect(GetNetworkNetworkCIDR6(&network), cidr6) {
return false
}
}
return true
}
func intersect(n1, n2 *net.IPNet) bool {
if n1 == nil || n2 == nil {
return false
}
return n2.Contains(n1.IP) || n1.Contains(n2.IP)
}
// IsNetworkNameUnique - checks to see if any other networks have the same name (id)
func IsNetworkNameUnique(ctx context.Context, network *schema.Network) (bool, error) {
_network := &schema.Network{
Name: network.Name,
}
err := _network.Get(ctx)
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return true, nil
}
return false, err
}
return false, nil
}
// UpdateNetwork - updates a network with another network's fields
func UpdateNetwork(ctx context.Context, currentNetwork, newNetwork *schema.Network) error {
if err := ValidateNetwork(ctx, newNetwork, true); err != nil {
return err
}
if newNetwork.Name != currentNetwork.Name {
return errors.New("failed to update network " + newNetwork.Name + ", cannot change netid.")
}
featureFlags := GetFeatureFlags(ctx)
if featureFlags.EnableDeviceApproval {
currentNetwork.AutoJoin = newNetwork.AutoJoin
} else {
currentNetwork.AutoJoin = true
}
currentNetwork.AutoRemove = newNetwork.AutoRemove
currentNetwork.AutoRemoveThreshold = newNetwork.AutoRemoveThreshold
currentNetwork.AutoRemoveTags = newNetwork.AutoRemoveTags
// Validate and update Virtual NAT IPv4 settings
if newNetwork.VirtualNATPoolIPv4 != "" {
_, poolNet, err := net.ParseCIDR(newNetwork.VirtualNATPoolIPv4)
if err != nil {
return fmt.Errorf("invalid Virtual NAT IPv4 pool CIDR: %w", err)
}
poolPrefixLen, _ := poolNet.Mask.Size()
if newNetwork.VirtualNATSitePrefixLenIPv4 <= 0 || newNetwork.VirtualNATSitePrefixLenIPv4 > 32 {
return fmt.Errorf("invalid Virtual NAT IPv4 site prefix length: must be between 1 and 32, got %d", newNetwork.VirtualNATSitePrefixLenIPv4)
}
// Validate that site prefix length is not larger (less specific) than pool prefix length
// e.g., pool /24 and site /8 is invalid because /8 is less specific (larger CIDR) than /24
// Site prefix must be >= pool prefix (more specific or equal)
if newNetwork.VirtualNATSitePrefixLenIPv4 < poolPrefixLen {
return fmt.Errorf("invalid Virtual NAT IPv4 site prefix length: site prefix length /%d cannot be larger (less specific) than pool prefix length /%d. Site prefix must be >= pool prefix (more specific or equal)", newNetwork.VirtualNATSitePrefixLenIPv4, poolPrefixLen)
}
currentNetwork.VirtualNATPoolIPv4 = newNetwork.VirtualNATPoolIPv4
currentNetwork.VirtualNATSitePrefixLenIPv4 = newNetwork.VirtualNATSitePrefixLenIPv4
} else if newNetwork.VirtualNATSitePrefixLenIPv4 > 0 {
// If pool is empty but site prefix is provided, validate against existing pool
if currentNetwork.VirtualNATPoolIPv4 != "" {
_, poolNet, err := net.ParseCIDR(currentNetwork.VirtualNATPoolIPv4)
if err == nil {
poolPrefixLen, _ := poolNet.Mask.Size()
if newNetwork.VirtualNATSitePrefixLenIPv4 > 32 {
return fmt.Errorf("invalid Virtual NAT IPv4 site prefix length: must be between 1 and 32, got %d", newNetwork.VirtualNATSitePrefixLenIPv4)
}
// Validate that site prefix length is not larger (less specific) than pool prefix length
if newNetwork.VirtualNATSitePrefixLenIPv4 < poolPrefixLen {
return fmt.Errorf("invalid Virtual NAT IPv4 site prefix length: site prefix length /%d cannot be larger (less specific) than pool prefix length /%d. Site prefix must be >= pool prefix (more specific or equal)", newNetwork.VirtualNATSitePrefixLenIPv4, poolPrefixLen)
}
}
}
currentNetwork.VirtualNATSitePrefixLenIPv4 = newNetwork.VirtualNATSitePrefixLenIPv4
}
// When both VNAT fields are omitted from the update, preserve existing settings
return currentNetwork.Update(ctx)
}
// validateNetName - checks if a netid of a network uses valid characters
func validateNetName(network *schema.Network) error {
var validationErr error
if len(network.Name) == 0 {
validationErr = errors.Join(validationErr, errors.New("network name cannot be empty"))
}
if len(network.Name) > 32 {
validationErr = errors.Join(validationErr, errors.New("network name cannot be longer than 32 characters"))
}
charset := "abcdefghijklmnopqrstuvwxyz1234567890-_"
for _, char := range network.Name {
if !strings.Contains(charset, string(char)) {
validationErr = errors.Join(validationErr, errors.New("invalid character(s) in network name"))
break
}
}
return validationErr
}
// Validate - validates fields of an network struct
func ValidateNetwork(ctx context.Context, network *schema.Network, isUpdate bool) error {
var validationErr error
err := validateNetName(network)
if err != nil {
validationErr = errors.Join(validationErr, err)
}
if !isUpdate {
nameUnique, _ := IsNetworkNameUnique(ctx, network)
if !nameUnique {
validationErr = errors.Join(validationErr, errors.New("invalid network name"))
}
}
if network.AddressRange != "" {
_, _, err = net.ParseCIDR(network.AddressRange)
if err != nil {
validationErr = errors.Join(validationErr, err)
}
}
if network.AddressRange6 != "" {
_, _, err = net.ParseCIDR(network.AddressRange6)
if err != nil {
validationErr = errors.Join(validationErr, err)
}
}
if network.DefaultKeepAlive > 1000 {
validationErr = errors.Join(validationErr, errors.New("default keep alive must be less than 1000"))
}
return validationErr
}
func NetworkExists(ctx context.Context, name string) (bool, error) {
err := (&schema.Network{Name: name}).Get(ctx)
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return false, nil
}
return false, err
}
return true, nil
}
// SortNetworks - Sorts slice of Networks by their NetID alphabetically with numbers first
func SortNetworks(unsortedNetworks []schema.Network) {
sort.Slice(unsortedNetworks, func(i, j int) bool {
return unsortedNetworks[i].Name < unsortedNetworks[j].Name
})
}
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
}
func GetTenantNetworkHookID(ctx context.Context) string {
return fmt.Sprintf("network-hook-%s", scope.ID(ctx))
}
func InitNetworkHooks(ctx context.Context) {
interval := 10
if GetServerSettings(ctx).CleanUpInterval > 0 {
interval = GetServerSettings(ctx).CleanUpInterval
}
HookManagerCh <- models.HookDetails{
ID: GetTenantNetworkHookID(ctx),
Hook: NetworkHook,
Params: []any{scope.ID(ctx)},
Interval: time.Duration(interval) * time.Minute,
}
}