fix: bootstrap admin CSRF tokens
This commit is contained in:
1 parent
a57c73055f
commit
b3245a18ea
8 files changed
+270
-45
No files matched your search
@@ -0,0 +1,41 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
cookies: vi.fn(),
|
||||
headers: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("next/headers", () => ({
|
||||
cookies: mocks.cookies,
|
||||
headers: mocks.headers,
|
||||
}));
|
||||
|
||||
import { readCsrfCookieToken } from "./security";
|
||||
|
||||
describe("readCsrfCookieToken", () => {
|
||||
beforeEach(() => {
|
||||
mocks.cookies.mockReset();
|
||||
});
|
||||
|
||||
it("reads an existing valid CSRF cookie without attempting a write", async () => {
|
||||
const token = "a".repeat(64);
|
||||
const set = vi.fn();
|
||||
mocks.cookies.mockResolvedValue({
|
||||
get: (name: string) =>
|
||||
name === "__Host-csrf-token" ? { value: token } : undefined,
|
||||
set,
|
||||
});
|
||||
|
||||
await expect(readCsrfCookieToken()).resolves.toBe(token);
|
||||
expect(set).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("returns an empty token when no valid cookie exists", async () => {
|
||||
mocks.cookies.mockResolvedValue({
|
||||
get: () => undefined,
|
||||
set: vi.fn(),
|
||||
});
|
||||
|
||||
await expect(readCsrfCookieToken()).resolves.toBe("");
|
||||
});
|
||||
});
|
||||
@@ -139,6 +139,16 @@ function trySetCsrfCookie(
|
||||
}
|
||||
}
|
||||
|
||||
/** Read-only access for Server Components, which cannot write response cookies. */
|
||||
export async function readCsrfCookieToken(): Promise<string> {
|
||||
try {
|
||||
return readExistingCsrfCookie(await cookies()) ?? "";
|
||||
} catch {
|
||||
logger.warn("Failed to read CSRF cookie");
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
/** Sets the CSRF cookie when possible; returns token or empty string (never throws). */
|
||||
export async function setCsrfCookie(): Promise<string> {
|
||||
try {
|
||||
|
||||
Reference in new issue
Block a user