// backend/utils/subnetFilter.js // ───────────────────────────────────────────────────────────────────────────── // Per-Agent Subnet Isolation & Auto-Pruning Helper // Enforces allowed_subnets configured in agent_registry at both DB and API level. // ───────────────────────────────────────────────────────────────────────────── const mongoose = require('mongoose'); const { DeviceStat, Flow, DeviceAppStat } = require('../models/Schemas'); let _subnetsCache = null; let _cacheTs = 0; const CACHE_TTL_MS = 30 * 1000; function invalidateSubnetCache() { _subnetsCache = null; _cacheTs = 0; } function ipToLong(ip) { if (!ip || typeof ip !== 'string') return 0; const parts = ip.trim().split('.'); if (parts.length !== 4) return 0; return parts.reduce((acc, oct) => (acc << 8) + (parseInt(oct, 10) || 0), 0) >>> 0; } function ipMatchesSubnets(ip, subnets) { if (!subnets || subnets.length === 0) return true; if (!ip || typeof ip !== 'string') return false; const cleanIp = ip.trim(); return subnets.some(raw => { const subnet = String(raw || '').trim(); if (!subnet) return false; if (subnet.includes('/')) { const [range, bitsStr] = subnet.split('/'); const bits = parseInt(bitsStr, 10); if (isNaN(bits) || bits < 0 || bits > 32) return false; const mask = bits === 0 ? 0 : (~0 << (32 - bits)) >>> 0; return (ipToLong(cleanIp) & mask) === (ipToLong(range) & mask); } return cleanIp.startsWith(subnet.endsWith('.') ? subnet : subnet + '.') || cleanIp === subnet; }); } function subnetToRegexStr(rawSubnet) { const subnet = String(rawSubnet || '').trim(); if (!subnet) return null; if (!subnet.includes('/')) { const clean = subnet.replace(/\.$/, '').replace(/\./g, '\\.'); return `^${clean}(\\.|$)`; } const [range, bitsStr] = subnet.split('/'); const bits = parseInt(bitsStr, 10); const octets = range.split('.').map(n => parseInt(n, 10) || 0); if (octets.length !== 4 || isNaN(bits) || bits < 8 || bits > 32) return null; if (bits === 8) return `^${octets[0]}\\.`; if (bits === 16) return `^${octets[0]}\\.${octets[1]}\\.`; if (bits === 24) return `^${octets[0]}\\.${octets[1]}\\.${octets[2]}\\.`; if (bits === 32) return `^${octets[0]}\\.${octets[1]}\\.${octets[2]}\\.${octets[3]}$`; if (bits > 8 && bits < 16) { const step = 1 << (16 - bits); const start = octets[1] & ~(step - 1); const vals = Array.from({ length: step }, (_, i) => start + i).join('|'); return `^${octets[0]}\\.(${vals})\\.`; } if (bits > 16 && bits < 24) { const step = 1 << (24 - bits); const start = octets[2] & ~(step - 1); const vals = Array.from({ length: step }, (_, i) => start + i).join('|'); return `^${octets[0]}\\.${octets[1]}\\.(${vals})\\.`; } if (bits > 24 && bits < 32) { const step = 1 << (32 - bits); const start = octets[3] & ~(step - 1); const vals = Array.from({ length: step }, (_, i) => start + i).join('|'); return `^${octets[0]}\\.${octets[1]}\\.${octets[2]}\\.(${vals})$`; } return null; } function buildSubnetsRegex(subnets) { if (!subnets || subnets.length === 0) return null; const parts = subnets.map(subnetToRegexStr).filter(Boolean); if (parts.length === 0) return null; return new RegExp(parts.join('|')); } async function getAgentSubnetsMap() { const now = Date.now(); if (_subnetsCache && (now - _cacheTs) < CACHE_TTL_MS) return _subnetsCache; try { if (!mongoose.connection?.db) return {}; const docs = await mongoose.connection.db .collection('agent_registry') .find({}, { projection: { uuid: 1, allowed_subnets: 1 } }) .toArray(); const map = {}; for (const d of docs) { if (d.uuid && Array.isArray(d.allowed_subnets)) { const clean = d.allowed_subnets.map(s => String(s).trim()).filter(Boolean); if (clean.length > 0) map[d.uuid] = clean; } } _subnetsCache = map; _cacheTs = now; return map; } catch (e) { return _subnetsCache || {}; } } async function applySubnetFilterToQuery(query, ipField = 'ip_address') { const map = await getAgentSubnetsMap(); if (typeof query.agent_uuid === 'string' && map[query.agent_uuid]) { const rx = buildSubnetsRegex(map[query.agent_uuid]); if (rx && !query[ipField]) { query[ipField] = { $regex: rx }; } } return map; } function filterRowsByAgentSubnets(rows, subnetsMap, ipField = 'ip_address', agentField = 'agent_uuid') { if (!subnetsMap || Object.keys(subnetsMap).length === 0) return rows; return rows.filter(r => { const agent = r[agentField]; const subnets = agent ? subnetsMap[agent] : null; if (!subnets || subnets.length === 0) return true; return ipMatchesSubnets(r[ipField], subnets); }); } async function pruneOutOfSubnetData() { try { invalidateSubnetCache(); const map = await getAgentSubnetsMap(); let totalDeletedDevs = 0, totalDeletedFlows = 0, totalDeletedApps = 0; for (const [agentUuid, subnets] of Object.entries(map)) { const rx = buildSubnetsRegex(subnets); if (!rx) continue; const [devRes, flowRes, appRes] = await Promise.all([ DeviceStat.deleteMany({ agent_uuid: agentUuid, ip_address: { $not: rx } }), Flow.deleteMany({ agent_uuid: agentUuid, src_ip: { $not: rx } }), DeviceAppStat.deleteMany({ agent_uuid: agentUuid, ip_address: { $not: rx } }), ]); totalDeletedDevs += devRes.deletedCount || 0; totalDeletedFlows += flowRes.deletedCount || 0; totalDeletedApps += appRes.deletedCount || 0; } if (totalDeletedDevs + totalDeletedFlows + totalDeletedApps > 0) { console.log(`[SubnetPruner] Cleaned out-of-subnet records: DeviceStat=${totalDeletedDevs}, Flow=${totalDeletedFlows}, DeviceAppStat=${totalDeletedApps}`); } return { totalDeletedDevs, totalDeletedFlows, totalDeletedApps }; } catch (err) { console.error('[SubnetPruner] Error:', err.message); return { totalDeletedDevs: 0, totalDeletedFlows: 0, totalDeletedApps: 0 }; } } module.exports = { invalidateSubnetCache, ipMatchesSubnets, buildSubnetsRegex, getAgentSubnetsMap, applySubnetFilterToQuery, filterRowsByAgentSubnets, pruneOutOfSubnetData, };