fix: address final review — cloud TLS, MAC guard, honest ISP metrics

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
zacharyandClaude Opus 5 committed 2026-10-08 00:23:44 +02:00
1 parent 1b312b3103
commit 277fbb841e
9 files changed
+227 -64

No files matched your search

@@ -1,5 +1,5 @@
// @vitest-environment node
import { Response } from "undici";
import { fetch as platformFetch, Response } from "undici";
import { beforeEach, describe, expect, test, vi } from "vitest";
vi.hoisted(() => {
@@ -17,7 +17,21 @@ vi.mock("@homarr/core/infrastructure/http", () => ({
fetchWithTrustedCertificatesAsync: vi.fn(),
}));
// Les deux transports sont mockés séparément parce qu'ils *doivent* rester
// séparés : le local passe par les certificats de confiance de Homarr, le cloud
// par le `fetch` de la plateforme. Mocker les deux permet d'affirmer qu'aucune
// requête vers api.ui.com n'emprunte le transport local — la garantie du §5.3.
vi.mock("undici", async (importOriginalAsync) => {
const actual = await importOriginalAsync<typeof import("undici")>();
return { ...actual, fetch: vi.fn() };
});
/** Transport local : certificats de confiance, console auto-signée. */
const mockFetch = vi.mocked(fetchWithTrustedCertificatesAsync);
/** Transport cloud : `fetch` de la plateforme, certificat public ordinaire. */
const mockCloudFetch = vi.mocked(platformFetch);
const CLOUD_ORIGIN = "https://api.ui.com";
const GATEWAY_MAC = "aa:bb:cc:11:22:33";
@@ -59,7 +73,6 @@ const localRoutes: Record<string, unknown> = {
memoryUtilizationPct: 63.1,
uplink: { txRateBps: 14140912, rxRateBps: 3346784 },
},
"/sites/site-1/vpn/servers": page([{ id: "v1", name: "vpn", enabled: true }]),
};
const routeLocal = (rawUrl: string): Response | null => {
@@ -83,8 +96,14 @@ const hybridSecrets: IntegrationSecret[] = [
{ kind: "siteManagerApiKey", value: "cloud-key" },
];
/** Toute URL demandée au transport local, quel que soit l'appelant. */
const localTransportUrls = () => mockFetch.mock.calls.map(([url]) => String(url));
/** Toute URL demandée au transport cloud. */
const cloudTransportUrls = () => mockCloudFetch.mock.calls.map(([url]) => String(url));
beforeEach(() => {
mockFetch.mockReset();
mockCloudFetch.mockReset();
UnifiSmApi.clearCache();
});
@@ -102,19 +121,23 @@ describe("UnifiOsIntegration getUnifiOsSummaryAsync", () => {
expect(summary.gateway).toMatchObject({ name: "Gateway", uptimeSec: 1009049, cpuPct: 19.1 });
});
test("leaves the ISP block null when no Site Manager key is configured", async () => {
test("leaves the ISP block null and touches no transport at all without a Site Manager key", async () => {
mockFetch.mockImplementation(async (url) => routeLocal(String(url)) ?? jsonResponse({}, 404));
const summary = await createIntegration(localOnlySecrets).getUnifiOsSummaryAsync();
expect(summary.wan.isp).toBeNull();
expect(mockFetch.mock.calls.every(([url]) => !String(url).startsWith("https://api.ui.com"))).toBe(true);
// Le transport cloud est le seul chemin vers api.ui.com : ne pas l'appeler
// du tout prouve qu'aucune requête cloud n'a été émise.
expect(mockCloudFetch).not.toHaveBeenCalled();
expect(localTransportUrls().every((url) => !url.startsWith(CLOUD_ORIGIN))).toBe(true);
});
test("fills the ISP block when a Site Manager key is configured", async () => {
mockFetch.mockImplementation(async (url) => {
test("fills the ISP block from the cloud transport, never from the trusted-certificate one", async () => {
mockFetch.mockImplementation(async (url) => routeLocal(String(url)) ?? jsonResponse({}, 404));
mockCloudFetch.mockImplementation(async (url) => {
const raw = String(url);
if (raw.startsWith("https://api.ui.com/v1/sites")) {
if (raw.startsWith(`${CLOUD_ORIGIN}/v1/sites`)) {
return jsonResponse({
data: [
{
@@ -144,13 +167,34 @@ describe("UnifiOsIntegration getUnifiOsSummaryAsync", () => {
},
});
}
return routeLocal(raw) ?? jsonResponse({}, 404);
return jsonResponse({}, 404);
});
const summary = await createIntegration(hybridSecrets).getUnifiOsSummaryAsync();
expect(summary.wan.isp).toMatchObject({ name: "Example ISP", latencyMs: 11, externalIp: "203.0.113.10" });
expect(summary.wan.isp?.measuredAt).toEqual(new Date("2026-09-08T09:10:00Z"));
// Le bloc ISP n'a pu être rempli que par des réponses servies par le mock
// cloud : les deux appels y sont donc bien passés.
expect(cloudTransportUrls()).toEqual([`${CLOUD_ORIGIN}/v1/sites`, `${CLOUD_ORIGIN}/v1/isp-metrics/5m/query`]);
// Le cœur du §5.3 : la clé Site Manager ne voyage jamais sur le transport
// qui embarque les autorités personnalisées de l'administrateur.
expect(localTransportUrls().every((url) => url.startsWith("https://console.example.test"))).toBe(true);
});
test("never sends the Site Manager key through the trusted-certificate transport", async () => {
mockFetch.mockImplementation(async (url) => routeLocal(String(url)) ?? jsonResponse({}, 404));
mockCloudFetch.mockImplementation(async () => jsonResponse({}, 500));
await createIntegration(hybridSecrets).getUnifiOsSummaryAsync();
const localKeys = mockFetch.mock.calls.map(
([, init]) => (init?.headers as Record<string, string> | undefined)?.["X-API-KEY"],
);
expect(localKeys.every((key) => key === "local-key")).toBe(true);
expect(localKeys).not.toContain("cloud-key");
});
test("degrades only the clients block when the clients endpoint fails", async () => {
@@ -127,6 +127,24 @@ describe("matchCloudSite", () => {
test("returns null when the local gateway is unknown", () => {
expect(matchCloudSite(null, [siteA, siteB])).toBeNull();
});
// `normalizeMacAddress` réduit "", "unknown" et "null" à la même chaîne vide.
// Sans garde, ces valeurs se correspondraient entre elles et le widget
// afficherait le réseau d'un autre compte comme celui de l'utilisateur.
test("returns null when the local MAC normalizes to nothing", () => {
const placeholder = { siteId: "placeholder", meta: { gatewayMac: "unknown" } };
for (const localMac of ["", "unknown", "null"]) {
expect(matchCloudSite(localMac, [placeholder, siteA, siteB])).toBeNull();
}
});
test("skips cloud sites whose gateway MAC normalizes to nothing", () => {
const placeholder = { siteId: "placeholder", meta: { gatewayMac: "unknown" } };
expect(matchCloudSite("aa:bb:cc:11:22:33", [placeholder, siteA])?.siteId).toBe("a");
expect(matchCloudSite("11:22:33:44:55:66", [placeholder])).toBeNull();
});
});
describe("unifiOsClientSchema", () => {
@@ -112,6 +112,34 @@ describe("UnifiSmApi getIspMetricsAsync", () => {
expect(metrics?.measuredAt).toEqual(new Date("2026-09-08T09:10:00Z"));
});
// Ubiquiti omet la latence pour les périodes où le WAN était coupé. Un `0`
// fabriqué s'afficherait comme « 0 ms » au pire moment possible.
test("passes missing cloud measurements through as null instead of zero", async () => {
const fetchAsync = vi.fn(async (url: string, _init?: RequestInit) => {
if (!url.includes("isp-metrics")) return jsonResponse(sitesBody);
return jsonResponse({
data: {
metrics: [
{
periods: [{ metricTime: "2026-09-08T09:10:00Z", data: { wan: { ispName: "Example ISP" } } }],
},
],
},
});
});
const api = new UnifiSmApi("cloud-key", fetchAsync as never);
const metrics = await api.getIspMetricsAsync(GATEWAY_MAC);
expect(metrics).toMatchObject({
latencyMs: null,
maxLatencyMs: null,
packetLossPct: null,
uptimePct: null,
});
});
test("returns null when no cloud site matches, never another account site", async () => {
const { api } = createApi();