Show new ports across every server on the Ports page, and mark them as expected there
A New badge, a notice with Show only new and Mark all as expected, and Mark as expected on each row. Uses the same rule as the alert and the server's Ports card. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
ccb863e7c3
commit
c79b2eda0d
7 files changed
+139
-13
No files matched your search
@@ -2,11 +2,13 @@ import { Router } from "express";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { z } from "zod";
|
||||
import { db } from "../db/client.js";
|
||||
import { servers, portForwards } from "../db/schema.js";
|
||||
import { servers, serverPorts, portForwards } from "../db/schema.js";
|
||||
import { requireAuth, requireRole } from "../auth/middleware.js";
|
||||
import { recordAudit } from "../services/audit.js";
|
||||
import { type AgentPort, groupAgentPorts, parseJson, splitPortKey } from "../services/agentPorts.js";
|
||||
import { listPresets, serviceName, serviceNames } from "../services/portPresets.js";
|
||||
import { newListeningPorts, parseBaseline, portKey } from "../services/newPorts.js";
|
||||
import { getSettings } from "../services/settingsStore.js";
|
||||
import { containerPortName, containerPortNames, type ContainerPortName } from "../services/containerPorts.js";
|
||||
import { asyncHandler } from "../utils/asyncHandler.js";
|
||||
|
||||
@@ -30,19 +32,34 @@ export interface AgentPortRow {
|
||||
/** The container that publishes it, as Dockhand says, when one does. */
|
||||
container: ContainerPortName | null;
|
||||
lastSeenAt: string | null;
|
||||
/** Began listening after the server's first report and nobody has noted it: a "new port" alert is on until it is noted or stops listening. */
|
||||
isNew: boolean;
|
||||
}
|
||||
|
||||
portsRouter.get("/agent", asyncHandler(async (_req, res) => {
|
||||
const rows = await db
|
||||
.select({ id: servers.id, name: servers.name, hostname: servers.hostname, listeningPorts: servers.listeningPorts, lastSeenAt: servers.lastSeenAt })
|
||||
.select({ id: servers.id, name: servers.name, hostname: servers.hostname, listeningPorts: servers.listeningPorts, portBaseline: servers.portBaseline, lastSeenAt: servers.lastSeenAt })
|
||||
.from(servers);
|
||||
|
||||
// Which are new: the rule the alert and the server's Ports card use — listening, reachable from outside, not in the baseline, and nobody has given the port a label or a comment.
|
||||
const alerting = (await getSettings()).healthChecks.newPortAlerts;
|
||||
const expectedByServer = new Map<number, Set<string>>();
|
||||
if (alerting) {
|
||||
for (const r of await db.select().from(serverPorts)) {
|
||||
if (!r.label && !r.comment) continue;
|
||||
const set = expectedByServer.get(r.serverId) ?? new Set<string>();
|
||||
set.add(portKey(r.protocol, r.port));
|
||||
expectedByServer.set(r.serverId, set);
|
||||
}
|
||||
}
|
||||
|
||||
const names = serviceNames(await listPresets());
|
||||
const containers = await containerPortNames();
|
||||
const out: AgentPortRow[] = [];
|
||||
for (const s of rows) {
|
||||
const raw = parseJson<AgentPort[] | null>(s.listeningPorts, null);
|
||||
if (!raw) continue;
|
||||
const fresh = new Set(alerting ? newListeningPorts(raw, parseBaseline(s.portBaseline), expectedByServer.get(s.id) ?? new Set()).map((p) => portKey(p.protocol, p.port)) : []);
|
||||
for (const [key, grouped] of groupAgentPorts(raw)) {
|
||||
const { protocol, port } = splitPortKey(key);
|
||||
out.push({
|
||||
@@ -57,6 +74,7 @@ portsRouter.get("/agent", asyncHandler(async (_req, res) => {
|
||||
service: serviceName(names, protocol, port),
|
||||
container: containerPortName(containers, s.id, protocol, port),
|
||||
lastSeenAt: s.lastSeenAt,
|
||||
isNew: fresh.has(key),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -30,6 +30,7 @@ const { startOrExtendWindow } = await import("../src/services/maintenance.js");
|
||||
const { metaOfConditionKey } = await import("../src/services/notifyRouting.js");
|
||||
const { subjectOfConditionKey } = await import("../src/services/maintenance.js");
|
||||
const { serverPortsRouter } = await import("../src/routes/serverPorts.js");
|
||||
const { portsRouter } = await import("../src/routes/ports.js");
|
||||
const { updateSettings } = await import("../src/services/settingsStore.js");
|
||||
const { eq } = await import("drizzle-orm");
|
||||
|
||||
@@ -94,6 +95,7 @@ describe("the health check, the alert and the routing", () => {
|
||||
describe("from a report to the Ports card", () => {
|
||||
let app: Server;
|
||||
let base = "";
|
||||
let origin = "";
|
||||
let serverId = 0;
|
||||
let who = "operator";
|
||||
const report = (ports: ReturnType<typeof sock>[]) => ({ tasks: [], system: { listening_ports: ports } });
|
||||
@@ -113,10 +115,12 @@ describe("from a report to the Ports card", () => {
|
||||
// The real servers router puts a signed-in user on the request before this; here the role is read the same way the middleware does.
|
||||
const { requireAuth } = await import("../src/auth/middleware.js");
|
||||
a.use("/api/servers/:id/ports", requireAuth, serverPortsRouter);
|
||||
a.use("/api/ports", portsRouter);
|
||||
app = await new Promise<Server>((resolve) => {
|
||||
const s = a.listen(0, "127.0.0.1", () => resolve(s));
|
||||
});
|
||||
base = `http://127.0.0.1:${(app.address() as AddressInfo).port}/api/servers/${serverId}/ports`;
|
||||
origin = `http://127.0.0.1:${(app.address() as AddressInfo).port}`;
|
||||
base = `${origin}/api/servers/${serverId}/ports`;
|
||||
});
|
||||
|
||||
after(() => {
|
||||
@@ -175,13 +179,33 @@ describe("from a report to the Ports card", () => {
|
||||
assert.deepEqual(await newKeys(), []);
|
||||
});
|
||||
|
||||
test("the Ports page, across every server, marks the same ports new — and noting one there is the same note", async () => {
|
||||
await syncServerTasks(serverId, report([sock(22), sock(443), sock(8080), sock(9999, { process: "python" })]));
|
||||
const [other] = await db.insert(servers).values({ name: "web", apiTokenHash: "w", apiTokenPrefix: "w" }).returning({ id: servers.id });
|
||||
await syncServerTasks(other.id, report([sock(80)]));
|
||||
await syncServerTasks(other.id, report([sock(80), sock(3000), sock(5353, { protocol: "udp" })]));
|
||||
who = "viewer";
|
||||
type Row = { serverId: number; port: number; protocol: string; isNew: boolean };
|
||||
const overview = async () => ((await (await fetch(`${origin}/api/ports/agent`)).json()).ports as Row[]);
|
||||
const fresh = async () => (await overview()).filter((p) => p.isNew).map((p) => `${p.serverId}:${p.protocol}/${p.port}`).sort();
|
||||
assert.deepEqual(await fresh(), [`${serverId}:tcp/9999`, `${other.id}:tcp/3000`].sort(), "what the baseline had, UDP and noted ports are not new");
|
||||
assert.equal((await overview()).filter((p) => p.serverId === serverId).length, 4, "every port is still listed, new or not");
|
||||
|
||||
who = "operator";
|
||||
const res = await fetch(base, { method: "PUT", headers: { "content-type": "application/json" }, body: JSON.stringify({ port: 9999, protocol: "tcp", label: "Expected" }) });
|
||||
assert.equal(res.status, 200);
|
||||
assert.deepEqual(await fresh(), [`${other.id}:tcp/3000`]);
|
||||
assert.deepEqual(await newKeys(), [], "and the alert ends with it");
|
||||
});
|
||||
|
||||
test("it can be switched off, and then nothing is new", async () => {
|
||||
await syncServerTasks(serverId, report([sock(22), sock(443), sock(8080), sock(9999)]));
|
||||
assert.deepEqual(await newKeys(), [9999]);
|
||||
await syncServerTasks(serverId, report([sock(22), sock(443), sock(8080), sock(9998)]));
|
||||
assert.deepEqual(await newKeys(), [9998]);
|
||||
await updateSettings({ healthChecks: { newPortAlerts: false } });
|
||||
assert.deepEqual(await newKeys(), []);
|
||||
who = "viewer";
|
||||
assert.equal(((await (await fetch(base)).json()).ports as { isNew: boolean }[]).some((p) => p.isNew), false);
|
||||
assert.equal(((await (await fetch(`${origin}/api/ports/agent`)).json()).ports as { isNew: boolean }[]).some((p) => p.isNew), false, "nor on the Ports page");
|
||||
await updateSettings({ healthChecks: { newPortAlerts: true } });
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user