Docker reuses the same subnet on many hosts, and those networks aren't part of the LAN, so they show up as conflicts and unlisted addresses. The report only knew about 172.16.0.0/12 through a hardcoded rule; Docker can just as well pick 192.168.x or 10.x. The Consistency page now has an Excluded ranges card: CIDR ranges (IPv4 or IPv6) and single addresses, added with a form and removed with one click, shown to everyone and editable by operators. There's also an "Exclude range" button on each finding that pre-fills a /24 (or /64) around its address to edit. Exclusions are applied to servers, IPAM and DNS before anything is compared, so an excluded address never appears in any kind of finding, whichever source it came from, and the card says how many addresses are currently being hidden so it's clear the filter is doing something. The old hardcoded rule becomes a visible default (172.16.0.0/12) that can be removed -- it was silently wrong for anyone using 172.16/12 as a real LAN. That default is also slightly stronger than before: an address in the range is now left out even if it is in IPAM or DNS, where the old rule only skipped it when nothing else mentioned it. Remove or narrow it if that isn't wanted. Ranges are validated and normalised on the server (both families, prefix bounds, no /0, at most 50), a bad one is rejected with a message naming it and nothing is saved, and changes are audit-logged with before/after. Matching uses Node's BlockList. Stored as a settings value; managed from the report rather than admin-only Settings, like ignoring a finding. Verified with 44 checks (range parsing and rejection, boundary addresses just inside and outside a range, IPv6, single addresses, exclusion across all sources and finding kinds, the hidden-address count, route validation/roles/audit) and in a browser against the real router: add, invalid, remove the default, exclude from a finding. Real dev database mtime untouched. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
251 lines
11 KiB
TypeScript
251 lines
11 KiB
TypeScript
import * as net from "node:net";
|
|
import { isPrivateAddress } from "./portScan.js";
|
|
|
|
/**
|
|
* Cross-checks the three places this app records what lives at an IP address — the IPAM inventory, the DNS records
|
|
* synced from the providers, and what each server's agent reports — and lists where they disagree. Pure: it takes
|
|
* plain data and returns findings, so every rule can be tested exactly.
|
|
*/
|
|
|
|
export type FindingKind = "ip_conflict" | "dns_stale" | "ipam_stale" | "not_in_ipam" | "no_dns";
|
|
export type Severity = "error" | "warning" | "info";
|
|
|
|
export interface ServerInput {
|
|
id: number;
|
|
name: string;
|
|
hostname: string | null;
|
|
/** What the agent last reported. Empty for a server with no agent or no report — such a server is never judged. */
|
|
ips: string[];
|
|
}
|
|
export interface IpamInput {
|
|
id: number;
|
|
ip: string;
|
|
label: string | null;
|
|
/** null = entered by hand; "tailscale"/"proxmox" = kept up to date by a sync. */
|
|
source: string | null;
|
|
}
|
|
export interface DnsInput {
|
|
name: string;
|
|
type: string;
|
|
content: string;
|
|
providerName: string;
|
|
}
|
|
|
|
export interface Finding {
|
|
/** Stable identity, so an ignored finding stays ignored across runs. */
|
|
key: string;
|
|
kind: FindingKind;
|
|
severity: Severity;
|
|
title: string;
|
|
detail: string;
|
|
ip: string | null;
|
|
servers: { id: number; name: string }[];
|
|
dnsNames: string[];
|
|
/** For not_in_ipam: a label to pre-fill when adding the address to IPAM. */
|
|
suggestedLabel: string | null;
|
|
}
|
|
|
|
// ─── helpers ────────────────────────────────────────────────────────────────
|
|
|
|
const norm = (ip: string) => ip.trim().toLowerCase();
|
|
const cleanName = (n: string) => n.trim().toLowerCase().replace(/\.$/, "");
|
|
const firstLabel = (n: string) => cleanName(n).split(".")[0];
|
|
|
|
// ─── Excluded ranges ────────────────────────────────────────────────────────
|
|
|
|
export const MAX_EXCLUDED_RANGES = 50;
|
|
export class InvalidRangeError extends Error {}
|
|
|
|
/** "10.0.0.0/8", "fd00::/8" or a single address, in a canonical lowercase form. Throws InvalidRangeError with a message fit to show. */
|
|
export function normalizeRange(input: string): string {
|
|
const text = input.trim().toLowerCase();
|
|
const [addr, prefixText, ...extra] = text.split("/");
|
|
const family = net.isIP(addr);
|
|
if (!text || extra.length > 0 || family === 0) {
|
|
throw new InvalidRangeError(`"${input.trim()}" isn't an address or range — use something like 192.168.16.0/20 or 10.1.2.3.`);
|
|
}
|
|
if (prefixText === undefined) return addr;
|
|
const max = family === 4 ? 32 : 128;
|
|
if (!/^\d{1,3}$/.test(prefixText) || Number(prefixText) > max) {
|
|
throw new InvalidRangeError(`"${input.trim()}": the part after the slash must be a number from 1 to ${max}.`);
|
|
}
|
|
if (Number(prefixText) === 0) throw new InvalidRangeError(`"${input.trim()}" would hide every address.`);
|
|
return `${addr}/${Number(prefixText)}`;
|
|
}
|
|
|
|
/** A matcher for a list of already-normalised ranges/addresses. */
|
|
export function makeExclusion(ranges: string[]): (ip: string) => boolean {
|
|
if (ranges.length === 0) return () => false;
|
|
const list = new net.BlockList();
|
|
for (const r of ranges) {
|
|
const [addr, prefix] = r.split("/");
|
|
const family = net.isIP(addr) === 6 ? "ipv6" : "ipv4";
|
|
if (prefix === undefined) list.addAddress(addr, family);
|
|
else list.addSubnet(addr, Number(prefix), family);
|
|
}
|
|
return (ip) => {
|
|
const family = net.isIP(ip);
|
|
return family !== 0 && list.check(ip, family === 6 ? "ipv6" : "ipv4");
|
|
};
|
|
}
|
|
|
|
/** How many distinct addresses the exclusions are currently hiding, so the page can show that they're doing something. */
|
|
export function countHiddenAddresses(input: { servers: ServerInput[]; ipam: IpamInput[]; dns: DnsInput[] }, ranges: string[]): number {
|
|
const excluded = makeExclusion(ranges);
|
|
const hidden = new Set<string>();
|
|
const consider = (ip: string) => {
|
|
const n = norm(ip);
|
|
if (excluded(n)) hidden.add(n);
|
|
};
|
|
for (const s of input.servers) s.ips.forEach(consider);
|
|
for (const e of input.ipam) consider(e.ip);
|
|
for (const r of input.dns) if (r.type === "A" || r.type === "AAAA") consider(r.content);
|
|
return hidden.size;
|
|
}
|
|
|
|
/** 100.64.0.0/10 — where Tailscale addresses live. MagicDNS names them, so a missing DNS record isn't a gap. */
|
|
function isCgnat(ip: string): boolean {
|
|
if (net.isIP(ip) !== 4) return false;
|
|
const [a, b] = ip.split(".").map(Number);
|
|
return a === 100 && b >= 64 && b <= 127;
|
|
}
|
|
|
|
/** Agents report IPv4 only, so an IPv6 record can't be judged against them (and vice versa) — only compare within a family. */
|
|
const sameFamilyAsAny = (ip: string, ips: string[]) => ips.some((o) => net.isIP(o) === net.isIP(ip));
|
|
|
|
const SEVERITY_ORDER: Record<Severity, number> = { error: 0, warning: 1, info: 2 };
|
|
|
|
/** Which of these servers does a DNS name or an IPAM label refer to? Exact hostname, or the same short name. */
|
|
function serversNamed(name: string, servers: ServerInput[]): ServerInput[] {
|
|
const n = cleanName(name);
|
|
const short = firstLabel(name);
|
|
return servers.filter((s) => {
|
|
const host = s.hostname ? cleanName(s.hostname) : null;
|
|
return (host !== null && n === host) || short === cleanName(s.name);
|
|
});
|
|
}
|
|
|
|
// ─── the checks ─────────────────────────────────────────────────────────────
|
|
|
|
/**
|
|
* `excludedRanges` are dropped from all three sources before anything is compared — an excluded address never
|
|
* appears in a finding, whichever side it came from. That's what lets Docker networks, which reuse the same subnet
|
|
* on many hosts and don't belong to the LAN, be kept out.
|
|
*/
|
|
export function buildFindings(input: { servers: ServerInput[]; ipam: IpamInput[]; dns: DnsInput[]; excludedRanges?: string[] }): Finding[] {
|
|
const findings: Finding[] = [];
|
|
const excluded = makeExclusion(input.excludedRanges ?? []);
|
|
const servers = input.servers.map((s) => ({ ...s, ips: [...new Set(s.ips.map(norm))].filter((ip) => !excluded(ip)) }));
|
|
const withIps = servers.filter((s) => s.ips.length > 0);
|
|
const ipamByIp = new Map(input.ipam.filter((e) => !excluded(norm(e.ip))).map((e) => [norm(e.ip), e]));
|
|
// Public DNS records are for the outside world, not this inventory — only private addresses are compared.
|
|
const privateDns = input.dns
|
|
.filter((r) => (r.type === "A" || r.type === "AAAA") && isPrivateAddress(r.content.trim()) && !excluded(norm(r.content)))
|
|
.map((r) => ({ ...r, name: cleanName(r.name), content: norm(r.content) }));
|
|
const dnsByIp = new Map<string, typeof privateDns>();
|
|
for (const r of privateDns) dnsByIp.set(r.content, [...(dnsByIp.get(r.content) ?? []), r]);
|
|
|
|
const add = (f: Omit<Finding, "servers" | "dnsNames" | "suggestedLabel" | "ip"> & Partial<Pick<Finding, "servers" | "dnsNames" | "suggestedLabel" | "ip">>) =>
|
|
findings.push({ servers: [], dnsNames: [], suggestedLabel: null, ip: null, ...f });
|
|
|
|
// 1. The same address reported by two servers.
|
|
const byServerIp = new Map<string, ServerInput[]>();
|
|
for (const s of withIps) for (const ip of s.ips) byServerIp.set(ip, [...(byServerIp.get(ip) ?? []), s]);
|
|
for (const [ip, owners] of byServerIp) {
|
|
if (owners.length < 2) continue;
|
|
add({
|
|
key: `ip_conflict|${ip}`,
|
|
kind: "ip_conflict",
|
|
severity: "error",
|
|
title: `${ip} is reported by ${owners.length} servers`,
|
|
detail: `${owners.map((o) => o.name).join(", ")} all claim this address — an IP conflict, or a stale agent report.`,
|
|
ip,
|
|
servers: owners.map((o) => ({ id: o.id, name: o.name })),
|
|
});
|
|
}
|
|
|
|
// 2. DNS names a server's own name, but pointing somewhere the server isn't.
|
|
const seenDns = new Set<string>();
|
|
for (const r of privateDns) {
|
|
for (const s of serversNamed(r.name, withIps)) {
|
|
if (s.ips.includes(r.content) || !sameFamilyAsAny(r.content, s.ips)) continue;
|
|
const key = `dns_stale|${s.id}|${r.name}|${r.content}`;
|
|
if (seenDns.has(key)) continue;
|
|
seenDns.add(key);
|
|
add({
|
|
key,
|
|
kind: "dns_stale",
|
|
severity: "warning",
|
|
title: `${r.name} points to ${r.content}, but ${s.name} reports ${s.ips.join(", ")}`,
|
|
detail: `The DNS record (${r.providerName}) doesn't match any address ${s.name} reports — likely out of date after an address change.`,
|
|
ip: r.content,
|
|
servers: [{ id: s.id, name: s.name }],
|
|
dnsNames: [r.name],
|
|
});
|
|
}
|
|
}
|
|
|
|
// 3. IPAM labels a server's name, at an address the server doesn't have.
|
|
for (const e of input.ipam) {
|
|
if (excluded(norm(e.ip))) continue;
|
|
if (!e.label || e.source === "tailscale" || e.source === "proxmox") continue; // kept current by their own syncs
|
|
const ip = norm(e.ip);
|
|
for (const s of serversNamed(e.label, withIps)) {
|
|
if (s.ips.includes(ip) || !sameFamilyAsAny(ip, s.ips)) continue;
|
|
add({
|
|
key: `ipam_stale|${s.id}|${ip}`,
|
|
kind: "ipam_stale",
|
|
severity: "warning",
|
|
title: `IPAM lists ${e.label} at ${ip}, but ${s.name} reports ${s.ips.join(", ")}`,
|
|
detail: `The IPAM entry doesn't match any address ${s.name} reports — update IPAM, or the server moved.`,
|
|
ip,
|
|
servers: [{ id: s.id, name: s.name }],
|
|
});
|
|
}
|
|
}
|
|
|
|
// 4. In use (a server reports it, or DNS points at it) but not in IPAM.
|
|
const candidates = new Set<string>([...byServerIp.keys(), ...dnsByIp.keys()]);
|
|
for (const ip of candidates) {
|
|
if (ipamByIp.has(ip)) continue;
|
|
const owners = byServerIp.get(ip) ?? [];
|
|
const records = dnsByIp.get(ip) ?? [];
|
|
const names = [...new Set(records.map((r) => r.name))];
|
|
const label = owners.length === 1 ? owners[0].name : names.length > 0 ? firstLabel(names[0]) : null;
|
|
const who = [...owners.map((o) => `reported by ${o.name}`), ...(names.length > 0 ? [`in DNS as ${names.join(", ")}`] : [])].join(" and ");
|
|
add({
|
|
key: `not_in_ipam|${ip}`,
|
|
kind: "not_in_ipam",
|
|
severity: records.length > 0 ? "warning" : "info",
|
|
title: `${ip} isn't in IPAM`,
|
|
detail: `${who}.`,
|
|
ip,
|
|
servers: owners.map((o) => ({ id: o.id, name: o.name })),
|
|
dnsNames: names,
|
|
suggestedLabel: label,
|
|
});
|
|
}
|
|
|
|
// 4b. A server address nothing in DNS points at — only meaningful once there are DNS records to compare against.
|
|
if (input.dns.length > 0) {
|
|
for (const s of withIps) {
|
|
for (const ip of s.ips) {
|
|
if (dnsByIp.has(ip) || net.isIP(ip) === 0 || !isPrivateAddress(ip) || isCgnat(ip)) continue;
|
|
add({
|
|
key: `no_dns|${s.id}|${ip}`,
|
|
kind: "no_dns",
|
|
severity: "info",
|
|
title: `No DNS record points at ${ip} (${s.name})`,
|
|
detail: `${s.name} reports ${ip}, but no cached A/AAAA record resolves to it.`,
|
|
ip,
|
|
servers: [{ id: s.id, name: s.name }],
|
|
});
|
|
}
|
|
}
|
|
}
|
|
|
|
return findings.sort(
|
|
(a, b) => SEVERITY_ORDER[a.severity] - SEVERITY_ORDER[b.severity] || a.kind.localeCompare(b.kind) || (a.ip ?? "").localeCompare(b.ip ?? "", undefined, { numeric: true }),
|
|
);
|
|
}
|