256 lines
9.9 KiB
TypeScript
256 lines
9.9 KiB
TypeScript
// @vitest-environment node
|
|
import { fetch as platformFetch, Response } from "undici";
|
|
import { beforeEach, describe, expect, test, vi } from "vitest";
|
|
|
|
vi.hoisted(() => {
|
|
process.env.SKIP_ENV_VALIDATION = "true";
|
|
process.env.SECRET_ENCRYPTION_KEY = "ff3f4f7ce30e870c9630de9e5d244ffa81101a24ed0dfe5f064beb53a7e684f1";
|
|
});
|
|
|
|
import { fetchWithTrustedCertificatesAsync } from "@homarr/core/infrastructure/http";
|
|
|
|
import type { IntegrationSecret } from "../../base/types";
|
|
import { UnifiSmApi } from "../unifi-sm-api";
|
|
import { UnifiOsIntegration } from "../unifi-os-integration";
|
|
|
|
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";
|
|
|
|
const jsonResponse = (body: unknown, status = 200) =>
|
|
new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } }) as never;
|
|
|
|
const page = (data: unknown[]) => ({ offset: 0, limit: 200, count: data.length, totalCount: data.length, data });
|
|
|
|
const localRoutes: Record<string, unknown> = {
|
|
"/info": { applicationVersion: "10.6.102" },
|
|
"/sites": page([{ id: "site-1", name: "Example site", internalReference: "default" }]),
|
|
"/sites/site-1/clients": page([
|
|
{ id: "c1", name: "a", type: "WIRED", access: { type: "DEFAULT" } },
|
|
{ id: "c2", name: "b", type: "WIRELESS", access: { type: "DEFAULT" } },
|
|
]),
|
|
"/sites/site-1/devices": page([
|
|
{
|
|
id: "gw",
|
|
name: "Gateway",
|
|
model: "UXG Pro",
|
|
macAddress: GATEWAY_MAC,
|
|
state: "ONLINE",
|
|
firmwareUpdatable: true,
|
|
features: ["gateway"],
|
|
},
|
|
{
|
|
id: "sw",
|
|
name: "Switch",
|
|
model: "USW Lite 8",
|
|
macAddress: "aa:bb:cc:99:88:77",
|
|
state: "OFFLINE",
|
|
firmwareUpdatable: false,
|
|
features: ["switching"],
|
|
},
|
|
]),
|
|
"/sites/site-1/devices/gw/statistics/latest": {
|
|
uptimeSec: 1009049,
|
|
cpuUtilizationPct: 19.1,
|
|
memoryUtilizationPct: 63.1,
|
|
uplink: { txRateBps: 14140912, rxRateBps: 3346784 },
|
|
},
|
|
};
|
|
|
|
const routeLocal = (rawUrl: string): Response | null => {
|
|
const path = new URL(rawUrl).pathname.replace("/proxy/network/integration/v1", "");
|
|
const body = localRoutes[path];
|
|
return body === undefined ? null : jsonResponse(body);
|
|
};
|
|
|
|
const createIntegration = (decryptedSecrets: IntegrationSecret[]) =>
|
|
new UnifiOsIntegration({
|
|
id: "test-unifi-os",
|
|
name: "Test UniFi OS",
|
|
url: "https://console.example.test",
|
|
externalUrl: null,
|
|
decryptedSecrets,
|
|
});
|
|
|
|
const localOnlySecrets: IntegrationSecret[] = [{ kind: "apiKey", value: "local-key" }];
|
|
const hybridSecrets: IntegrationSecret[] = [
|
|
{ kind: "apiKey", value: "local-key" },
|
|
{ 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();
|
|
});
|
|
|
|
describe("UnifiOsIntegration getUnifiOsSummaryAsync", () => {
|
|
test("builds the summary from the local API alone", async () => {
|
|
mockFetch.mockImplementation(async (url) => routeLocal(String(url)) ?? jsonResponse({}, 404));
|
|
|
|
const summary = await createIntegration(localOnlySecrets).getUnifiOsSummaryAsync();
|
|
|
|
expect(summary.site).toEqual({ id: "site-1", name: "Example site", applicationVersion: "10.6.102" });
|
|
expect(summary.clients).toEqual({ total: 2, wired: 1, wireless: 1, vpn: 0, guests: 0 });
|
|
expect(summary.devices).toEqual({ total: 2, online: 1, offline: 1, firmwareUpdatable: 1 });
|
|
expect(summary.wan.state).toBe("online");
|
|
expect(summary.wan.throughput).toEqual({ txBps: 14140912, rxBps: 3346784 });
|
|
expect(summary.gateway).toMatchObject({ name: "Gateway", uptimeSec: 1009049, cpuPct: 19.1 });
|
|
});
|
|
|
|
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();
|
|
// 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 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(`${CLOUD_ORIGIN}/v1/sites`)) {
|
|
return jsonResponse({
|
|
data: [
|
|
{
|
|
siteId: "cloud-1",
|
|
hostId: "host-1",
|
|
meta: { gatewayMac: GATEWAY_MAC },
|
|
statistics: { wans: { WAN: { externalIp: "203.0.113.10" } } },
|
|
},
|
|
],
|
|
});
|
|
}
|
|
if (raw.includes("isp-metrics")) {
|
|
return jsonResponse({
|
|
data: {
|
|
metrics: [
|
|
{
|
|
periods: [
|
|
{
|
|
metricTime: "2026-09-08T09:10:00Z",
|
|
data: {
|
|
wan: { avgLatency: 11, maxLatency: 12, packetLoss: 0, uptime: 100, ispName: "Example ISP" },
|
|
},
|
|
},
|
|
],
|
|
},
|
|
],
|
|
},
|
|
});
|
|
}
|
|
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 () => {
|
|
mockFetch.mockImplementation(async (url) => {
|
|
const raw = String(url);
|
|
if (raw.includes("/clients")) return jsonResponse({ error: "boom" }, 500);
|
|
return routeLocal(raw) ?? jsonResponse({}, 404);
|
|
});
|
|
|
|
const summary = await createIntegration(localOnlySecrets).getUnifiOsSummaryAsync();
|
|
|
|
expect(summary.clients).toBeNull();
|
|
expect(summary.devices).toEqual({ total: 2, online: 1, offline: 1, firmwareUpdatable: 1 });
|
|
expect(summary.gateway).not.toBeNull();
|
|
});
|
|
|
|
test("degrades only the devices block when the devices endpoint fails", async () => {
|
|
mockFetch.mockImplementation(async (url) => {
|
|
const raw = String(url);
|
|
if (raw.includes("/devices") && !raw.includes("/statistics")) return jsonResponse({ error: "boom" }, 500);
|
|
return routeLocal(raw) ?? jsonResponse({}, 404);
|
|
});
|
|
|
|
const summary = await createIntegration(localOnlySecrets).getUnifiOsSummaryAsync();
|
|
|
|
expect(summary.devices).toBeNull();
|
|
expect(summary.clients).toEqual({ total: 2, wired: 1, wireless: 1, vpn: 0, guests: 0 });
|
|
});
|
|
|
|
test("keeps clients and devices when the gateway cannot be identified", async () => {
|
|
mockFetch.mockImplementation(async (url) => {
|
|
const raw = String(url);
|
|
if (raw.endsWith("/devices?limit=200")) {
|
|
return jsonResponse(
|
|
page([
|
|
{
|
|
id: "sw",
|
|
name: "Switch",
|
|
model: "USW Lite 8",
|
|
macAddress: "aa:bb:cc:99:88:77",
|
|
state: "ONLINE",
|
|
firmwareUpdatable: false,
|
|
features: ["switching"],
|
|
},
|
|
]),
|
|
);
|
|
}
|
|
return routeLocal(raw) ?? jsonResponse({}, 404);
|
|
});
|
|
|
|
const summary = await createIntegration(localOnlySecrets).getUnifiOsSummaryAsync();
|
|
|
|
expect(summary.gateway).toBeNull();
|
|
expect(summary.wan.throughput).toBeNull();
|
|
expect(summary.wan.state).toBe("unknown");
|
|
expect(summary.clients).toEqual({ total: 2, wired: 1, wireless: 1, vpn: 0, guests: 0 });
|
|
});
|
|
});
|