Bulk snooze, alert rules judged on report, photos on notes
Bulk snooze: Snooze... and Wake on the ticked alerts, with undo that puts back each alert's earlier snooze exactly. Alert rules are judged for a server right after its agent reports, instead of at the next 15-minute pass; only that server's rule findings change, and the check is serialized with the pass so neither overwrites the other's state. Photos on server and device notes: up to 12 each, shrunk in the browser, accepted by their own bytes (JPEG/PNG/GIF/WebP, 4 MB), kept in the database and removed with the server or device. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
251a4a9d73
commit
a16996d975
27 files changed
+8442
-54
No files matched your search
@@ -0,0 +1,178 @@
|
||||
/**
|
||||
* Photos on notes: what is accepted (told by the bytes, never by the name or the type claimed), the limits, who may add and who may only look, how a picture is served, and that
|
||||
* removing the server or the device removes its photos.
|
||||
*
|
||||
* Run with: npm test --workspace server
|
||||
*/
|
||||
import { test, describe, before, after } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { mkdtempSync, rmSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import type { AddressInfo } from "node:net";
|
||||
import type { Server } from "node:http";
|
||||
|
||||
const dir = mkdtempSync(join(tmpdir(), "hm-note-photos-"));
|
||||
process.env.DATABASE_PATH = join(dir, "test.sqlite");
|
||||
process.env.SESSION_DIR = join(dir, "sessions");
|
||||
process.env.CREDENTIALS_ENCRYPTION_KEY = "ab".repeat(32);
|
||||
process.env.HEALTH_STARTUP_GRACE_MS = "0";
|
||||
|
||||
const express = (await import("express")).default;
|
||||
const { db } = await import("../src/db/client.js");
|
||||
const { users, servers, integrations, networkDevices, notePhotos, auditLog } = await import("../src/db/schema.js");
|
||||
const { runMigrations } = await import("../src/db/migrate.js");
|
||||
const { sniffImage, MAX_PHOTO_BYTES, MAX_PHOTOS_PER_TARGET, MAX_CAPTION } = await import("../src/services/notePhotos.js");
|
||||
const { notePhotosRouter } = await import("../src/routes/notePhotos.js");
|
||||
const { getChangeLog } = await import("../src/services/changeLog.js");
|
||||
const { eq } = await import("drizzle-orm");
|
||||
|
||||
await runMigrations();
|
||||
|
||||
const png = (extra = 0) => Buffer.concat([Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]), Buffer.alloc(32 + extra, 7)]);
|
||||
const jpeg = () => Buffer.concat([Buffer.from([0xff, 0xd8, 0xff, 0xe0]), Buffer.alloc(32, 3)]);
|
||||
const gif = () => Buffer.concat([Buffer.from("GIF89a", "latin1"), Buffer.alloc(32, 1)]);
|
||||
const webp = () => Buffer.concat([Buffer.from("RIFF", "latin1"), Buffer.from([0x20, 0, 0, 0]), Buffer.from("WEBP", "latin1"), Buffer.alloc(24, 2)]);
|
||||
|
||||
describe("what counts as a picture", () => {
|
||||
test("a JPEG, a PNG, a GIF and a WebP are told by how they begin", () => {
|
||||
assert.equal(sniffImage(jpeg()), "image/jpeg");
|
||||
assert.equal(sniffImage(png()), "image/png");
|
||||
assert.equal(sniffImage(gif()), "image/gif");
|
||||
assert.equal(sniffImage(webp()), "image/webp");
|
||||
});
|
||||
|
||||
test("an SVG, a page, a script, an empty or a truncated file are none of them", () => {
|
||||
for (const bad of ['<svg xmlns="http://www.w3.org/2000/svg"><script>alert(1)</script></svg>', "<!doctype html><title>x</title>", "#!/bin/sh\nrm -rf /", ""]) assert.equal(sniffImage(Buffer.from(bad)), null, bad.slice(0, 20));
|
||||
assert.equal(sniffImage(Buffer.from([0x89, 0x50, 0x4e])), null);
|
||||
assert.equal(sniffImage(Buffer.concat([Buffer.from("RIFF", "latin1"), Buffer.alloc(4), Buffer.from("WAVE", "latin1")])), null, "RIFF, but not WebP");
|
||||
});
|
||||
});
|
||||
|
||||
describe("photos through the routes", () => {
|
||||
let app: Server;
|
||||
let base = "";
|
||||
let who = "operator";
|
||||
const ids: Record<string, number> = {};
|
||||
|
||||
const send = async (path: string, init: { method?: string; body?: Buffer | string; type?: string } = {}) => {
|
||||
const res = await fetch(`${base}${path}`, { method: init.method ?? "GET", headers: init.type ? { "content-type": init.type } : undefined, body: init.body });
|
||||
const text = res.headers.get("content-type")?.includes("json") ? await res.json() : null;
|
||||
return { status: res.status, res, body: text as any };
|
||||
};
|
||||
const upload = (target: string, type: "server" | "device", bytes: Buffer, caption = "", claimed = "image/png") =>
|
||||
send(`/api/note-photos?targetType=${type}&targetId=${ids[target]}${caption ? `&caption=${encodeURIComponent(caption)}` : ""}`, { method: "POST", body: bytes, type: claimed });
|
||||
|
||||
before(async () => {
|
||||
await db.insert(users).values([
|
||||
{ oidcSub: "operator", name: "Olga", role: "operator" },
|
||||
{ oidcSub: "viewer", name: "Vic", role: "viewer" },
|
||||
]);
|
||||
ids.rack = (await db.insert(servers).values({ name: "rack-pc", apiTokenHash: "r", apiTokenPrefix: "r" }).returning({ id: servers.id }))[0].id;
|
||||
ids.other = (await db.insert(servers).values({ name: "other", apiTokenHash: "o", apiTokenPrefix: "o" }).returning({ id: servers.id }))[0].id;
|
||||
const [unifi] = await db.insert(integrations).values({ type: "unifi", name: "UniFi", baseUrl: "http://10.0.0.1", config: "{}" }).returning({ id: integrations.id });
|
||||
ids.switch = (await db.insert(networkDevices).values({ integrationId: unifi.id, externalId: "aa:bb:cc:dd:ee:ff", name: "core switch", kind: "switch", firstSeenAt: new Date().toISOString(), updatedAt: new Date().toISOString() }).returning({ id: networkDevices.id }))[0].id;
|
||||
const a = express();
|
||||
a.use(express.json());
|
||||
a.use((req, _res, next) => {
|
||||
(req as unknown as { session: unknown }).session = { user: { sub: who } };
|
||||
next();
|
||||
});
|
||||
a.use("/api/note-photos", notePhotosRouter);
|
||||
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}`;
|
||||
});
|
||||
after(() => {
|
||||
app.close();
|
||||
try {
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
} catch {
|
||||
// Windows keeps the database file locked until the process exits.
|
||||
}
|
||||
});
|
||||
|
||||
test("an operator adds a photo with a caption; it is listed, and served with its own type and a policy that lets it run nothing", async () => {
|
||||
const r = await upload("rack", "server", png(), " The back of the rack ");
|
||||
assert.equal(r.status, 201);
|
||||
assert.deepEqual([r.body.photo.caption, r.body.photo.contentType, r.body.photo.createdBy, r.body.photo.size], ["The back of the rack", "image/png", "Olga", png().length]);
|
||||
const list = await send(`/api/note-photos?targetType=server&targetId=${ids.rack}`);
|
||||
assert.deepEqual(list.body.photos.map((p: { id: number }) => p.id), [r.body.photo.id]);
|
||||
const img = await send(`/api/note-photos/${r.body.photo.id}/image`);
|
||||
assert.equal(img.status, 200);
|
||||
assert.equal(img.res.headers.get("content-type"), "image/png");
|
||||
assert.equal(img.res.headers.get("x-content-type-options"), "nosniff");
|
||||
assert.match(img.res.headers.get("content-security-policy") ?? "", /sandbox/);
|
||||
assert.match(img.res.headers.get("cache-control") ?? "", /immutable/);
|
||||
assert.deepEqual(Buffer.from(await img.res.arrayBuffer()), png(), "exactly the bytes that were sent");
|
||||
});
|
||||
|
||||
test("what the picture is comes from its bytes: a PNG sent as something else is a PNG; a script sent as image/png is refused", async () => {
|
||||
const ok = await upload("rack", "server", jpeg(), "", "application/octet-stream");
|
||||
assert.equal(ok.body.photo.contentType, "image/jpeg");
|
||||
const bad = await upload("rack", "server", Buffer.from('<svg xmlns="http://www.w3.org/2000/svg"><script>alert(1)</script></svg>'), "", "image/png");
|
||||
assert.deepEqual([bad.status, bad.body.error], [400, "not_an_image"]);
|
||||
assert.equal((await upload("rack", "server", Buffer.alloc(0))).status, 400);
|
||||
});
|
||||
|
||||
test("a device's photos are its own, and a photo can be of a device as well as of a server", async () => {
|
||||
const r = await upload("switch", "device", gif(), "Port labels");
|
||||
assert.equal(r.status, 201);
|
||||
assert.equal((await send(`/api/note-photos?targetType=device&targetId=${ids.switch}`)).body.photos.length, 1);
|
||||
assert.equal((await send(`/api/note-photos?targetType=server&targetId=${ids.other}`)).body.photos.length, 0);
|
||||
});
|
||||
|
||||
test("a photo over 4 MB is refused with a plain message; one that is not for anything is not found", async () => {
|
||||
const big = await upload("other", "server", png(MAX_PHOTO_BYTES));
|
||||
assert.equal(big.status, 413);
|
||||
assert.equal(big.body.error, "too_big");
|
||||
const nowhere = await send(`/api/note-photos?targetType=server&targetId=999999`, { method: "POST", body: png(), type: "image/png" });
|
||||
assert.equal(nowhere.status, 404);
|
||||
assert.equal((await send(`/api/note-photos?targetType=thing&targetId=1`, { method: "POST", body: png(), type: "image/png" })).status, 400);
|
||||
});
|
||||
|
||||
test("a thing has at most twelve photos", async () => {
|
||||
await db.delete(notePhotos).where(eq(notePhotos.serverId, ids.other));
|
||||
for (let i = 0; i < MAX_PHOTOS_PER_TARGET; i++) assert.equal((await upload("other", "server", webp())).status, 201);
|
||||
const r = await upload("other", "server", webp());
|
||||
assert.deepEqual([r.status, r.body.error], [400, "too_many"]);
|
||||
});
|
||||
|
||||
test("a caption is kept short and can be changed or cleared; a photo can be removed, and the change log says so", async () => {
|
||||
const [photo] = await db.select().from(notePhotos).where(eq(notePhotos.serverId, ids.rack));
|
||||
const long = await send(`/api/note-photos/${photo.id}`, { method: "PUT", body: JSON.stringify({ caption: "x".repeat(MAX_CAPTION + 50) }), type: "application/json" });
|
||||
assert.equal(long.body.photo.caption.length, MAX_CAPTION);
|
||||
const cleared = await send(`/api/note-photos/${photo.id}`, { method: "PUT", body: JSON.stringify({ caption: " " }), type: "application/json" });
|
||||
assert.equal(cleared.body.photo.caption, null);
|
||||
assert.equal((await send(`/api/note-photos/999999`, { method: "PUT", body: JSON.stringify({ caption: "x" }), type: "application/json" })).status, 404);
|
||||
assert.equal((await send(`/api/note-photos/${photo.id}`, { method: "DELETE" })).status, 204);
|
||||
assert.equal((await send(`/api/note-photos/${photo.id}/image`)).status, 404);
|
||||
assert.equal((await send(`/api/note-photos/${photo.id}`, { method: "DELETE" })).status, 404);
|
||||
const actions = (await db.select().from(auditLog)).map((e) => `${e.category}/${e.action}`);
|
||||
assert.ok(actions.includes("note/photo_add") && actions.includes("note/photo_delete"));
|
||||
const titles = (await getChangeLog({ days: 1, limit: 200 })).entries.map((e) => e.title);
|
||||
assert.ok(titles.some((t) => /^A photo was added to a note on rack-pc$/.test(t)), "added");
|
||||
assert.ok(titles.some((t) => /^A photo was removed from a note on rack-pc$/.test(t)), "removed");
|
||||
});
|
||||
|
||||
test("everyone signed in can look; only an operator can add, caption or remove", async () => {
|
||||
who = "viewer";
|
||||
const [photo] = await db.select().from(notePhotos).where(eq(notePhotos.serverId, ids.other));
|
||||
assert.equal((await send(`/api/note-photos?targetType=server&targetId=${ids.other}`)).status, 200);
|
||||
assert.equal((await send(`/api/note-photos/${photo.id}/image`)).status, 200);
|
||||
assert.equal((await upload("other", "server", png())).status, 403);
|
||||
assert.equal((await send(`/api/note-photos/${photo.id}`, { method: "PUT", body: JSON.stringify({ caption: "x" }), type: "application/json" })).status, 403);
|
||||
assert.equal((await send(`/api/note-photos/${photo.id}`, { method: "DELETE" })).status, 403);
|
||||
who = "operator";
|
||||
});
|
||||
|
||||
test("removing the server or the device removes its photos", async () => {
|
||||
assert.ok((await db.select().from(notePhotos).where(eq(notePhotos.serverId, ids.other))).length > 0);
|
||||
await db.delete(servers).where(eq(servers.id, ids.other));
|
||||
assert.equal((await db.select().from(notePhotos).where(eq(notePhotos.serverId, ids.other))).length, 0);
|
||||
assert.equal((await db.select().from(notePhotos).where(eq(notePhotos.deviceId, ids.switch))).length, 1);
|
||||
await db.delete(networkDevices).where(eq(networkDevices.id, ids.switch));
|
||||
assert.equal((await db.select().from(notePhotos).where(eq(notePhotos.deviceId, ids.switch))).length, 0);
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user