300 lines
11 KiB
TypeScript
300 lines
11 KiB
TypeScript
import { afterEach, describe, expect, it } from "vitest";
|
|
import type { FastifyInstance } from "fastify";
|
|
import { buildApp } from "../src/app.js";
|
|
import type { AppConfig } from "../src/config.js";
|
|
import { CSRF_COOKIE, SESSION_COOKIE } from "../src/security.js";
|
|
|
|
const apps: FastifyInstance[] = [];
|
|
|
|
function testConfig(): AppConfig {
|
|
return {
|
|
nodeEnv: "test",
|
|
host: "127.0.0.1",
|
|
port: 8787,
|
|
databasePath: ":memory:",
|
|
sessionTtlMs: 60_000,
|
|
cookieSecure: false,
|
|
allowedOrigins: new Set(["http://mg4pi.local:8787"]),
|
|
updateStatusPath: `/tmp/pi-car-companion-test-${process.pid}-missing-update.json`,
|
|
versionFile: `/tmp/pi-car-companion-test-${process.pid}-missing-revision`,
|
|
network: {
|
|
enabled: false,
|
|
statusPath: `/tmp/pi-car-companion-test-${process.pid}-missing-network-status.json`,
|
|
commandPath: `/tmp/pi-car-companion-test-${process.pid}-network-command.json`,
|
|
configurationRequestPath: `/tmp/pi-car-companion-test-${process.pid}-network-configuration.json`,
|
|
activityPath: `/tmp/pi-car-companion-test-${process.pid}-network-activity.json`
|
|
},
|
|
adb: { enabled: false, executable: "adb", serial: null, timeoutMs: 3_000 }
|
|
};
|
|
}
|
|
|
|
async function createApp(): Promise<FastifyInstance> {
|
|
const app = await buildApp(testConfig());
|
|
apps.push(app);
|
|
return app;
|
|
}
|
|
|
|
async function csrf(app: FastifyInstance): Promise<string> {
|
|
const response = await app.inject({ method: "GET", url: "/api/auth/state" });
|
|
expect(response.statusCode).toBe(200);
|
|
return response.json<{ csrfToken: string }>().csrfToken;
|
|
}
|
|
|
|
function mutationHeaders(token: string) {
|
|
return {
|
|
cookie: `${CSRF_COOKIE}=${token}`,
|
|
"x-csrf-token": token,
|
|
origin: "http://mg4pi.local:8787"
|
|
};
|
|
}
|
|
|
|
async function setup(app: FastifyInstance, token: string) {
|
|
return app.inject({
|
|
method: "POST",
|
|
url: "/api/auth/setup",
|
|
headers: mutationHeaders(token),
|
|
payload: { username: "owner", password: "Correct-horse1" }
|
|
});
|
|
}
|
|
|
|
afterEach(async () => {
|
|
await Promise.all(apps.splice(0).map((app) => app.close()));
|
|
});
|
|
|
|
describe("authentication boundary", () => {
|
|
it("creates exactly one initial administrator", async () => {
|
|
const app = await createApp();
|
|
const token = await csrf(app);
|
|
|
|
expect((await setup(app, token)).statusCode).toBe(201);
|
|
const second = await app.inject({
|
|
method: "POST",
|
|
url: "/api/auth/setup",
|
|
headers: mutationHeaders(token),
|
|
payload: { username: "second", password: "Another-pass2" }
|
|
});
|
|
|
|
expect(second.statusCode).toBe(409);
|
|
expect(second.json()).toMatchObject({ error: { code: "SETUP_COMPLETE" } });
|
|
});
|
|
|
|
it("requires 8 characters, an uppercase letter, and a number for setup", async () => {
|
|
const app = await createApp();
|
|
const token = await csrf(app);
|
|
const cases = [
|
|
{ password: "Short1", expectedMessage: "at least 8 characters" },
|
|
{ password: "lowercase1", expectedMessage: "uppercase letter" },
|
|
{ password: "NoNumberHere", expectedMessage: "one number" }
|
|
];
|
|
|
|
for (const testCase of cases) {
|
|
const response = await app.inject({
|
|
method: "POST",
|
|
url: "/api/auth/setup",
|
|
headers: mutationHeaders(token),
|
|
payload: { username: "owner", password: testCase.password }
|
|
});
|
|
expect(response.statusCode).toBe(400);
|
|
expect(response.json<{ error: { message: string } }>().error.message).toContain(testCase.expectedMessage);
|
|
}
|
|
});
|
|
|
|
it("rejects state changes without a matching CSRF token", async () => {
|
|
const app = await createApp();
|
|
const response = await app.inject({
|
|
method: "POST",
|
|
url: "/api/auth/setup",
|
|
payload: { username: "owner", password: "Correct-horse1" }
|
|
});
|
|
|
|
expect(response.statusCode).toBe(403);
|
|
expect(response.json()).toMatchObject({ error: { code: "CSRF_REJECTED" } });
|
|
});
|
|
|
|
it("rejects an untrusted browser origin", async () => {
|
|
const app = await createApp();
|
|
const token = await csrf(app);
|
|
const response = await app.inject({
|
|
method: "POST",
|
|
url: "/api/auth/setup",
|
|
headers: { ...mutationHeaders(token), origin: "https://attacker.example" },
|
|
payload: { username: "owner", password: "Correct-horse1" }
|
|
});
|
|
|
|
expect(response.statusCode).toBe(403);
|
|
expect(response.json()).toMatchObject({ error: { code: "ORIGIN_REJECTED" } });
|
|
});
|
|
|
|
it("accepts a same-host origin for dynamic LAN addresses", async () => {
|
|
const app = await createApp();
|
|
const token = await csrf(app);
|
|
const response = await app.inject({
|
|
method: "POST",
|
|
url: "/api/auth/setup",
|
|
headers: {
|
|
...mutationHeaders(token),
|
|
host: "192.168.4.20:8787",
|
|
origin: "http://192.168.4.20:8787"
|
|
},
|
|
payload: { username: "owner", password: "Correct-horse1" }
|
|
});
|
|
|
|
expect(response.statusCode).toBe(201);
|
|
});
|
|
|
|
it("requires a valid session for system status", async () => {
|
|
const app = await createApp();
|
|
expect((await app.inject({ method: "GET", url: "/api/status" })).statusCode).toBe(401);
|
|
|
|
const token = await csrf(app);
|
|
await setup(app, token);
|
|
const login = await app.inject({
|
|
method: "POST",
|
|
url: "/api/auth/login",
|
|
headers: mutationHeaders(token),
|
|
payload: { username: "owner", password: "Correct-horse1" }
|
|
});
|
|
expect(login.statusCode).toBe(200);
|
|
const sessionCookie = login.cookies.find((cookie) => cookie.name === SESSION_COOKIE);
|
|
expect(sessionCookie).toBeDefined();
|
|
|
|
const status = await app.inject({
|
|
method: "GET",
|
|
url: "/api/status",
|
|
headers: { cookie: `${SESSION_COOKIE}=${sessionCookie?.value ?? ""}` }
|
|
});
|
|
expect(status.statusCode, status.body).toBe(200);
|
|
expect(status.json()).toMatchObject({
|
|
service: { state: "healthy" },
|
|
headUnit: { available: false, state: "disabled" }
|
|
});
|
|
|
|
const update = await app.inject({
|
|
method: "POST",
|
|
url: "/api/system/update",
|
|
headers: {
|
|
...mutationHeaders(token),
|
|
cookie: `${CSRF_COOKIE}=${token}; ${SESSION_COOKIE}=${sessionCookie?.value ?? ""}`
|
|
}
|
|
});
|
|
expect(update.statusCode).toBe(503);
|
|
expect(update.json()).toMatchObject({ error: { code: "UPDATES_UNAVAILABLE" } });
|
|
|
|
const check = await app.inject({
|
|
method: "POST",
|
|
url: "/api/system/update/check",
|
|
headers: {
|
|
...mutationHeaders(token),
|
|
cookie: `${CSRF_COOKIE}=${token}; ${SESSION_COOKIE}=${sessionCookie?.value ?? ""}`
|
|
}
|
|
});
|
|
expect(check.statusCode).toBe(503);
|
|
expect(check.json()).toMatchObject({ error: { code: "UPDATES_UNAVAILABLE" } });
|
|
|
|
const invalidPower = await app.inject({
|
|
method: "POST",
|
|
url: "/api/system/power",
|
|
headers: {
|
|
...mutationHeaders(token),
|
|
cookie: `${CSRF_COOKIE}=${token}; ${SESSION_COOKIE}=${sessionCookie?.value ?? ""}`
|
|
},
|
|
payload: { action: "factory-reset" }
|
|
});
|
|
expect(invalidPower.statusCode).toBe(400);
|
|
expect(invalidPower.json()).toMatchObject({ error: { code: "INVALID_POWER_ACTION" } });
|
|
});
|
|
|
|
it("does not expose update state without authentication", async () => {
|
|
const app = await createApp();
|
|
const response = await app.inject({ method: "GET", url: "/api/system/update" });
|
|
expect(response.statusCode).toBe(401);
|
|
});
|
|
|
|
it("keeps network status and controls behind authentication and explicit configuration", async () => {
|
|
const app = await createApp();
|
|
expect((await app.inject({ method: "GET", url: "/api/network" })).statusCode).toBe(401);
|
|
expect((await app.inject({ method: "GET", url: "/api/network/activity" })).statusCode).toBe(401);
|
|
|
|
const token = await csrf(app);
|
|
await setup(app, token);
|
|
const login = await app.inject({
|
|
method: "POST",
|
|
url: "/api/auth/login",
|
|
headers: mutationHeaders(token),
|
|
payload: { username: "owner", password: "Correct-horse1" }
|
|
});
|
|
const session = login.cookies.find((item) => item.name === SESSION_COOKIE)?.value ?? "";
|
|
const cookie = `${CSRF_COOKIE}=${token}; ${SESSION_COOKIE}=${session}`;
|
|
const status = await app.inject({ method: "GET", url: "/api/network", headers: { cookie } });
|
|
expect(status.statusCode).toBe(200);
|
|
expect(status.json()).toMatchObject({ supported: false, enabled: false, mode: "disabled" });
|
|
const activity = await app.inject({ method: "GET", url: "/api/network/activity", headers: { cookie } });
|
|
expect(activity.statusCode).toBe(200);
|
|
expect(activity.json()).toMatchObject({ supported: false, clients: [], dnsQueries: [], flows: [] });
|
|
|
|
const action = await app.inject({
|
|
method: "POST",
|
|
url: "/api/network/actions",
|
|
headers: { ...mutationHeaders(token), cookie },
|
|
payload: { action: "retry-upstream" }
|
|
});
|
|
expect(action.statusCode).toBe(503);
|
|
|
|
const invalidConfiguration = await app.inject({
|
|
method: "POST",
|
|
url: "/api/network/configuration",
|
|
headers: { ...mutationHeaders(token), cookie },
|
|
payload: { ssid: "bad/name", password: "short" }
|
|
});
|
|
expect(invalidConfiguration.statusCode).toBe(400);
|
|
expect(invalidConfiguration.json()).toMatchObject({ error: { code: "INVALID_HOTSPOT_CONFIGURATION" } });
|
|
});
|
|
|
|
it("exposes only allowlisted jobs and authenticated run history", async () => {
|
|
const app = await createApp();
|
|
const token = await csrf(app);
|
|
await setup(app, token);
|
|
const login = await app.inject({
|
|
method: "POST",
|
|
url: "/api/auth/login",
|
|
headers: mutationHeaders(token),
|
|
payload: { username: "owner", password: "Correct-horse1" }
|
|
});
|
|
const session = login.cookies.find((item) => item.name === SESSION_COOKIE)?.value ?? "";
|
|
const cookie = `${CSRF_COOKIE}=${token}; ${SESSION_COOKIE}=${session}`;
|
|
|
|
expect((await app.inject({ method: "GET", url: "/api/jobs" })).statusCode).toBe(401);
|
|
const jobs = await app.inject({ method: "GET", url: "/api/jobs", headers: { cookie } });
|
|
expect(jobs.statusCode).toBe(200);
|
|
expect(jobs.json<{ jobs: { id: string }[] }>().jobs.map((job) => job.id)).toEqual([
|
|
"refresh-health",
|
|
"network-diagnostics",
|
|
"support-bundle"
|
|
]);
|
|
|
|
const unknown = await app.inject({
|
|
method: "POST",
|
|
url: "/api/jobs/arbitrary-shell/runs",
|
|
headers: { ...mutationHeaders(token), cookie }
|
|
});
|
|
expect(unknown.statusCode).toBe(404);
|
|
expect(unknown.json()).toMatchObject({ error: { code: "JOB_NOT_FOUND" } });
|
|
|
|
const queued = await app.inject({
|
|
method: "POST",
|
|
url: "/api/jobs/refresh-health/runs",
|
|
headers: { ...mutationHeaders(token), cookie }
|
|
});
|
|
expect(queued.statusCode).toBe(202);
|
|
const runId = queued.json<{ id: string }>().id;
|
|
let run: { status: string } = { status: "queued" };
|
|
for (let attempt = 0; attempt < 50 && ["queued", "running"].includes(run.status); attempt += 1) {
|
|
await new Promise((resolve) => setTimeout(resolve, 2));
|
|
const response = await app.inject({ method: "GET", url: `/api/job-runs/${runId}`, headers: { cookie } });
|
|
expect(response.statusCode).toBe(200);
|
|
run = response.json<{ status: string }>();
|
|
}
|
|
expect(run.status).toBe("succeeded");
|
|
});
|
|
});
|