Files
bookmanager/tests/unit/security.test.ts
T
bobbanandClaude Sonnet 5.5 dcb5d43429 Automatiska tester, och rättningar som testerna hittade
Vitest med enhetstester utan databas och databastester mot en egen
testdatabas vars namn måste sluta på _test. Rättar tomma MAP_*-värden
i .env och säkerhetskopior med å, ä och ö i filnamnet.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-01 23:19:30 +01:00

60 lines
2.6 KiB
TypeScript

import { afterEach, describe, expect, it, vi } from "vitest";
import { contentSecurityPolicy, runtimeSecurityHeaders } from "@/lib/security";
afterEach(() => vi.unstubAllEnvs());
const directive = (csp: string, name: string) => csp.split("; ").find((d) => d.startsWith(`${name} `)) ?? "";
describe("Content-Security-Policy", () => {
it("släpper igenom OpenStreetMap som standard", () => {
vi.stubEnv("MAP_TILE_URL", "");
vi.stubEnv("MAP_GEOCODER_URL", "");
// Tomma värden (t.ex. "MAP_TILE_URL=" i .env) ska ge standard
const csp = contentSecurityPolicy();
expect(directive(csp, "img-src")).toContain("https://tile.openstreetmap.org");
expect(directive(csp, "connect-src")).toContain("https://nominatim.openstreetmap.org");
expect(csp).toContain("frame-ancestors 'none'");
expect(csp).toContain("object-src 'none'");
expect(csp).toContain("base-uri 'self'");
});
it("använder adresserna från MAP_TILE_URL och MAP_GEOCODER_URL", () => {
vi.stubEnv("MAP_TILE_URL", "https://tiles.example.com/{z}/{x}/{y}.png");
vi.stubEnv("MAP_GEOCODER_URL", "https://geo.example.com/search");
const csp = contentSecurityPolicy();
expect(csp).toMatch(/img-src [^;]*https:\/\/tiles\.example\.com/);
expect(csp).toMatch(/connect-src [^;]*https:\/\/geo\.example\.com/);
expect(csp).not.toContain("openstreetmap.org");
});
it("tillåter underdomäner när tilladressen har {s}", () => {
vi.stubEnv("MAP_TILE_URL", "https://{s}.tiles.example.com/{z}/{x}/{y}.png");
expect(contentSecurityPolicy()).toContain("https://*.tiles.example.com");
});
it("tillåter inte eval i produktion men gör det vid utveckling", () => {
vi.stubEnv("NODE_ENV", "production");
expect(contentSecurityPolicy()).not.toContain("unsafe-eval");
vi.stubEnv("NODE_ENV", "development");
expect(contentSecurityPolicy()).toContain("unsafe-eval");
});
it("ignorerar en trasig adress i stället för att krascha", () => {
vi.stubEnv("MAP_TILE_URL", "inte en adress");
expect(() => contentSecurityPolicy()).not.toThrow();
});
});
describe("runtimeSecurityHeaders", () => {
it("sätter HSTS bara när AUTH_URL är https", () => {
vi.stubEnv("AUTH_URL", "https://bocker.example.com");
expect(runtimeSecurityHeaders()["Strict-Transport-Security"]).toContain("max-age=");
vi.stubEnv("AUTH_URL", "http://localhost:3000");
expect(runtimeSecurityHeaders()["Strict-Transport-Security"]).toBeUndefined();
});
it("innehåller alltid en policy", () => {
expect(runtimeSecurityHeaders()["Content-Security-Policy"]).toContain("default-src 'self'");
});
});