Add a "Sync from Proxmox" action to IP Addresses (IPAM)

Extends the Tailscale IPAM sync to Proxmox: pulls every VM/LXC's IP
address(es) across all enabled Proxmox integrations into the
inventory, reusing the same never-overwrite-a-manual-entry semantics.

Proxmox guests can have multiple NICs (each IP synced as its own
entry) and, for QEMU VMs, IP discovery depends on a responsive guest
agent — a VM with none simply contributes zero entries rather than
erroring, matching getGuestDetail()'s existing best-effort behavior.
listGuests() doesn't include IPs, so this fetches getGuestDetail() per
guest; acceptable for an explicit, user-triggered sync rather than a
background poll.

Extracted the shared "insert, update only if I own this row, else
skip and report" upsert logic (previously inline in the Tailscale sync
handler) into upsertSyncedEntry(), now used by both sync routes so the
core safety rule can't drift between them.

Verified end-to-end against a mock Proxmox server covering: an LXC
with two NICs (both synced), a QEMU VM with a responsive guest agent,
a QEMU VM with no agent (zero entries, no error), a manual-entry
collision (skipped and reported, never overwritten), and idempotent
re-sync (add -> update on the second run).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
bobbanandClaude Sonnet 5 committed 2026-09-15 23:45:10 +02:00
1 parent d714a87754
commit e7ac6fea3b
4 files changed
+122 -27

No files matched your search

+99 -11
View File
@@ -9,6 +9,7 @@ import { recordAudit } from "../services/audit.js";
import { asyncHandler } from "../utils/asyncHandler.js";
import { loadIntegrationConfig } from "../integrations/loadIntegration.js";
import { createTailscaleAdapter } from "../integrations/tailscale/adapter.js";
import { createProxmoxAdapter } from "../integrations/proxmox/adapter.js";
export const ipamRouter = Router();
@@ -129,6 +130,34 @@ ipamRouter.delete("/:id", requireRole("operator"), asyncHandler(async (req, res)
res.status(204).end();
}));
/**
* Inserts a new IPAM entry for `ip`, or updates one this same sync source
* previously created — but never touches an entry that already exists from
* a manual entry or a different sync source, so two syncs (or a sync and a
* human) can never clobber each other.
*/
async function upsertSyncedEntry(
ip: string,
label: string,
vendor: string,
notes: string | null,
source: string,
): Promise<"added" | "updated" | "skipped"> {
const [existing] = await db.select().from(ipamEntries).where(eq(ipamEntries.ipAddress, ip)).limit(1);
if (!existing) {
await db.insert(ipamEntries).values({ ipAddress: ip, label, vendor, notes, source });
return "added";
}
if (existing.source === source) {
await db
.update(ipamEntries)
.set({ label, notes, updatedAt: new Date().toISOString() })
.where(eq(ipamEntries.id, existing.id));
return "updated";
}
return "skipped";
}
ipamRouter.post("/sync-tailscale", requireRole("operator"), asyncHandler(async (req, res) => {
const tailscaleIntegrations = await db
.select()
@@ -164,17 +193,10 @@ ipamRouter.post("/sync-tailscale", requireRole("operator"), asyncHandler(async (
const label = device.label || device.hostname || ip;
const notes = device.os ? `OS: ${device.os}` : null;
const [existing] = await db.select().from(ipamEntries).where(eq(ipamEntries.ipAddress, ip)).limit(1);
if (!existing) {
await db.insert(ipamEntries).values({ ipAddress: ip, label, vendor: "Tailscale", notes, source: "tailscale" });
added++;
} else if (existing.source === "tailscale") {
await db
.update(ipamEntries)
.set({ label, notes, updatedAt: new Date().toISOString() })
.where(eq(ipamEntries.id, existing.id));
updated++;
} else {
const result = await upsertSyncedEntry(ip, label, "Tailscale", notes, "tailscale");
if (result === "added") added++;
else if (result === "updated") updated++;
else {
skipped++;
skippedIps.push(ip);
}
@@ -190,3 +212,69 @@ ipamRouter.post("/sync-tailscale", requireRole("operator"), asyncHandler(async (
res.json({ added, updated, skipped, skippedIps, errors });
}));
ipamRouter.post("/sync-proxmox", requireRole("operator"), asyncHandler(async (req, res) => {
const proxmoxIntegrations = await db
.select()
.from(integrations)
.where(and(eq(integrations.type, "proxmox"), eq(integrations.enabled, true)));
if (proxmoxIntegrations.length === 0) {
return res.status(400).json({ error: "no_proxmox_integration" });
}
let added = 0;
let updated = 0;
let skipped = 0;
const skippedIps: string[] = [];
const errors: string[] = [];
for (const integration of proxmoxIntegrations) {
const loaded = await loadIntegrationConfig(integration.id);
if (!loaded || loaded.integration.type !== "proxmox") continue;
const adapter = createProxmoxAdapter(
loaded.config as { url: string; tokenId: string; tokenSecret: string; insecure?: boolean },
);
let guests;
try {
guests = await adapter.listGuests();
} catch (err) {
errors.push(`${integration.name}: ${err instanceof Error ? err.message : String(err)}`);
continue;
}
for (const guest of guests) {
let detail;
try {
detail = await adapter.getGuestDetail(guest.node, guest.type, guest.vmid);
} catch (err) {
errors.push(`${integration.name}/${guest.name}: ${err instanceof Error ? err.message : String(err)}`);
continue;
}
const label = guest.name || `${guest.type}/${guest.vmid}`;
const notes = `Proxmox ${guest.type === "qemu" ? "VM" : "LXC"} #${guest.vmid} on ${guest.node}`;
for (const ip of detail.ipAddresses) {
const result = await upsertSyncedEntry(ip, label, "Proxmox", notes, "proxmox");
if (result === "added") added++;
else if (result === "updated") updated++;
else {
skipped++;
skippedIps.push(ip);
}
}
}
}
await recordAudit({
actor: req.currentUser!,
category: "ipam",
action: "sync_proxmox",
detail: { added, updated, skipped },
});
res.json({ added, updated, skipped, skippedIps, errors });
}));