diff --git a/web/middleware.test.ts b/web/middleware.test.ts new file mode 100644 index 0000000..94426e3 --- /dev/null +++ b/web/middleware.test.ts @@ -0,0 +1,49 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; +import { NextResponse, NextRequest } from "next/server"; + +// updateSession telefoniert normalerweise ueber das Netz zu Supabase +// (supabase.auth.getUser()). Fuer einen schnellen, deterministischen Test +// stubben wir es und pruefen nur, ob die Middleware es aufruft oder umgeht. +vi.mock("@/lib/supabase/middleware", () => ({ + updateSession: vi.fn(), +})); + +import { updateSession } from "@/lib/supabase/middleware"; +import { middleware } from "@/middleware"; + +beforeEach(() => { + vi.mocked(updateSession).mockReset(); + vi.mocked(updateSession).mockImplementation(async (request) => { + const url = request.nextUrl.clone(); + url.pathname = "/login"; + return NextResponse.redirect(url); + }); +}); + +describe("middleware", () => { + it("laesst POST /api/notifications/dispatch ohne Session-Cookie ohne Redirect passieren", async () => { + const request = new NextRequest("http://localhost/api/notifications/dispatch", { + method: "POST", + }); + + const res = await middleware(request); + + // Session-Gate (updateSession) darf fuer diese Route gar nicht laufen + expect(updateSession).not.toHaveBeenCalled(); + // Kein 3xx-Redirect nach /login + expect(res.status).toBe(200); + const location = res.headers.get("location"); + expect(location === null || !location.endsWith("/login")).toBe(true); + }); + + it("leitet GET /dashboard ohne Session-Cookie weiterhin auf /login um", async () => { + const request = new NextRequest("http://localhost/dashboard", { method: "GET" }); + + const res = await middleware(request); + + expect(updateSession).toHaveBeenCalledTimes(1); + expect(res.status).toBeGreaterThanOrEqual(300); + expect(res.status).toBeLessThan(400); + expect(res.headers.get("location")).toMatch(/\/login$/); + }); +}); diff --git a/web/middleware.ts b/web/middleware.ts index 4fb87fb..a14caab 100644 --- a/web/middleware.ts +++ b/web/middleware.ts @@ -1,7 +1,13 @@ -import { type NextRequest } from "next/server"; +import { NextResponse, type NextRequest } from "next/server"; import { updateSession } from "@/lib/supabase/middleware"; export async function middleware(request: NextRequest) { + // Interne Endpunkte mit eigener Authentifizierung (Shared Secret) umgehen + // das Supabase-Session-Gating -- der pg_cron-Aufruf an diese Route traegt + // kein Session-Cookie. + if (request.nextUrl.pathname === "/api/notifications/dispatch") { + return NextResponse.next(); + } return await updateSession(request); }