Files
HiveGrid-Wireframes/03 Quellen und Referenzen/hivegrid-cloud/apps/web/app/routes/new-account.csrf.test.tsx
T

345 lines
15 KiB
TypeScript

import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
import { beforeEach, describe, expect, it, vi } from "vitest";
const { checkAuthRateLimitMock } = vi.hoisted(() => ({
checkAuthRateLimitMock: vi.fn(async () => ({ allowed: true as const })),
}));
const { TenantSlugCollisionErrorMock } = vi.hoisted(() => ({
TenantSlugCollisionErrorMock: class TenantSlugCollisionError extends Error {},
}));
vi.mock("~/components/screens/auth/CreateWorkspacePage", () => ({ CreateWorkspacePage: () => null }));
vi.mock("~/lib/metrics/ssr", () => ({ withMetrics: (_name: string, handler: unknown) => handler }));
vi.mock("~/utils/session.server", () => ({
getUserInfo: vi.fn(async () => ({ userId: "user_1" })),
validateCSRFToken: vi.fn(),
}));
vi.mock("~/utils/api/.server/TenantsApi", () => ({
TenantsApi: {
create: vi.fn(async () => ({ tenant: { id: "tenant_1", slug: "acme" }, user: { id: "user_1" } })),
},
}));
vi.mock("~/utils/db/tenants.db.server", () => ({
getMyTenants: vi.fn(async () => []),
TenantSlugCollisionError: TenantSlugCollisionErrorMock,
}));
vi.mock("~/domain/tenant-bootstrap/tenantBootstrapService.server", () => ({
isExactOwnedTenantCreationReplay: vi.fn(async () => false),
}));
vi.mock("~/utils/db/users.db.server", () => ({ getUser: vi.fn(async () => ({ id: "user_1" })) }));
vi.mock("~/locale/i18next.server", () => ({
getTranslations: vi.fn(async () => ({ t: (key: string) => `translated:${key}` })),
}));
vi.mock("~/services/auth/auth-rate-limit.server", () => ({
checkAuthRateLimit: checkAuthRateLimitMock,
}));
const sessionServer = await import("~/utils/session.server");
const tenantsApi = await import("~/utils/api/.server/TenantsApi");
const tenantsDb = await import("~/utils/db/tenants.db.server");
const usersDb = await import("~/utils/db/users.db.server");
const tenantBootstrap = await import("~/domain/tenant-bootstrap/tenantBootstrapService.server");
const { action, loader } = await import("./new-account");
describe("new-account route", () => {
beforeEach(() => {
vi.clearAllMocks();
vi.mocked(sessionServer.getUserInfo).mockResolvedValue({ userId: "user_1" } as never);
vi.mocked(sessionServer.validateCSRFToken).mockResolvedValue(undefined as never);
vi.mocked(tenantsApi.TenantsApi.create).mockResolvedValue({ tenant: { id: "tenant_1", slug: "acme" }, user: { id: "user_1" } } as never);
vi.mocked(tenantsDb.getMyTenants).mockResolvedValue([] as never);
vi.mocked(usersDb.getUser).mockResolvedValue({ id: "user_1" } as never);
vi.mocked(tenantBootstrap.isExactOwnedTenantCreationReplay).mockResolvedValue(false);
checkAuthRateLimitMock.mockResolvedValue({ allowed: true });
});
it("redirects to login when the loader cannot find the user", async () => {
vi.mocked(usersDb.getUser).mockResolvedValueOnce(null as never);
try {
await loader({
request: new Request("https://app.example.com/new-account"),
params: {},
context: {},
} as unknown as LoaderFunctionArgs);
throw new Error("Expected loader to throw a redirect response");
} catch (error) {
expect(error).toBeInstanceOf(Response);
const response = error as Response;
expect(response.status).toBe(302);
expect(response.headers.get("Location")).toBe("/login");
}
expect(sessionServer.getUserInfo).toHaveBeenCalledWith(expect.any(Request));
expect(usersDb.getUser).toHaveBeenCalledWith("user_1");
expect(tenantsDb.getMyTenants).not.toHaveBeenCalled();
});
it("loads the current user's tenants", async () => {
const creationRequestKey = "d7077797-054b-497a-b1ce-8e4f36257a96";
const myTenants = [{ id: "tenant_1", name: "Acme", slug: "acme" }];
vi.mocked(tenantsDb.getMyTenants).mockResolvedValueOnce(myTenants as never);
const data = await loader({
request: new Request(`https://app.example.com/new-account?creationRequestKey=${creationRequestKey}`),
params: {},
context: {},
} as unknown as LoaderFunctionArgs);
expect(data).toEqual({
myTenants,
creationRequestKey,
});
expect(sessionServer.getUserInfo).toHaveBeenCalledWith(expect.any(Request));
expect(usersDb.getUser).toHaveBeenCalledWith("user_1");
expect(tenantsDb.getMyTenants).toHaveBeenCalledWith("user_1");
});
it("redirects once to a reload-stable creation key and reuses it on the canonical URL", async () => {
let canonicalLocation = "";
try {
await loader({
request: new Request("https://app.example.com/new-account"),
params: {},
context: {},
} as unknown as LoaderFunctionArgs);
throw new Error("Expected loader to throw a redirect response");
} catch (error) {
expect(error).toBeInstanceOf(Response);
const response = error as Response;
expect(response.status).toBe(302);
canonicalLocation = response.headers.get("Location") ?? "";
expect(canonicalLocation).toMatch(/^\/new-account\?creationRequestKey=[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i);
}
const canonicalUrl = new URL(canonicalLocation, "https://app.example.com");
const data = await loader({
request: new Request(canonicalUrl),
params: {},
context: {},
} as unknown as LoaderFunctionArgs);
expect(data.creationRequestKey).toBe(canonicalUrl.searchParams.get("creationRequestKey"));
});
it("validates CSRF before atomically creating the owned tenant", async () => {
const creationRequestKey = "d7077797-054b-497a-b1ce-8e4f36257a96";
const body = new URLSearchParams({ name: "Acme", slug: "acme", csrf: "csrf-token", creationRequestKey });
const request = new Request("https://app.example.com/new-account", {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body,
});
const response = (await action({
request,
params: {},
context: {},
} as unknown as ActionFunctionArgs)) as Response;
expect(response.status).toBe(302);
expect(response.headers.get("Location")).toBe("/acme/dashboard");
expect(sessionServer.validateCSRFToken).toHaveBeenCalledWith(request);
expect(tenantsApi.TenantsApi.create).toHaveBeenCalledTimes(1);
const createArgs = vi.mocked(tenantsApi.TenantsApi.create).mock.calls[0]?.[0];
expect(createArgs).toMatchObject({ request, name: "Acme", slug: "acme", creationRequestKey });
});
it("rejects a missing or malformed creation request key before tenant creation", async () => {
const request = new Request("https://app.example.com/new-account", {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: new URLSearchParams({ name: "Acme", csrf: "csrf-token", creationRequestKey: "attacker-controlled" }),
});
const response = (await action({ request, params: {}, context: {} } as unknown as ActionFunctionArgs)) as Response;
expect(response.status).toBe(400);
await expect(response.json()).resolves.toEqual({ error: "translated:app.tenants.create.errors.invalidRequest" });
expect(sessionServer.validateCSRFToken).toHaveBeenCalledWith(request);
expect(tenantsApi.TenantsApi.create).not.toHaveBeenCalled();
});
it("rejects a blank workspace name before tenant creation", async () => {
const creationRequestKey = "d7077797-054b-497a-b1ce-8e4f36257a96";
const request = new Request("https://app.example.com/new-account", {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: new URLSearchParams({
name: " ",
csrf: "csrf-token",
creationRequestKey,
}),
});
const response = (await action({ request, params: {}, context: {} } as unknown as ActionFunctionArgs)) as Response;
expect(response.status).toBe(400);
await expect(response.json()).resolves.toEqual({ error: "translated:app.tenants.create.errors.nameRequired", creationRequestKey });
expect(checkAuthRateLimitMock).not.toHaveBeenCalled();
expect(tenantsApi.TenantsApi.create).not.toHaveBeenCalled();
});
it("rate-limits expensive workspace bootstraps per authenticated user", async () => {
const creationRequestKey = "d7077797-054b-497a-b1ce-8e4f36257a96";
checkAuthRateLimitMock.mockResolvedValueOnce({ allowed: true }).mockResolvedValueOnce({ allowed: false, retryAfterSeconds: 47 });
const request = new Request("https://app.example.com/new-account", {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: new URLSearchParams({ name: "Acme", csrf: "csrf-token", creationRequestKey }),
});
const response = (await action({ request, params: {}, context: {} } as unknown as ActionFunctionArgs)) as Response;
expect(response.status).toBe(429);
expect(response.headers.get("Retry-After")).toBe("47");
expect(response.headers.get("Cache-Control")).toBe("no-store");
await expect(response.json()).resolves.toEqual({
error: "translated:app.tenants.create.errors.tooManyRequests",
creationRequestKey,
});
expect(checkAuthRateLimitMock).toHaveBeenNthCalledWith(1, {
request,
action: "workspace-create-attempt",
identifier: "user_1",
limit: 30,
windowMs: 900_000,
});
expect(checkAuthRateLimitMock).toHaveBeenNthCalledWith(2, {
request,
action: "workspace-create",
identifier: "user_1",
limit: 3,
windowMs: 86_400_000,
});
expect(tenantsApi.TenantsApi.create).not.toHaveBeenCalled();
});
it("bounds replay classification before it opens a database transaction", async () => {
const creationRequestKey = "d7077797-054b-497a-b1ce-8e4f36257a96";
checkAuthRateLimitMock.mockResolvedValueOnce({ allowed: false, retryAfterSeconds: 12 });
const request = new Request("https://app.example.com/new-account", {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: new URLSearchParams({ name: "Acme", csrf: "csrf-token", creationRequestKey }),
});
const response = (await action({ request, params: {}, context: {} } as unknown as ActionFunctionArgs)) as Response;
expect(response.status).toBe(429);
expect(response.headers.get("Retry-After")).toBe("12");
expect(tenantBootstrap.isExactOwnedTenantCreationReplay).not.toHaveBeenCalled();
expect(tenantsApi.TenantsApi.create).not.toHaveBeenCalled();
});
it("does not let repeated post-commit recovery attempts exhaust the new-workspace quota", async () => {
const creationRequestKey = "d7077797-054b-497a-b1ce-8e4f36257a96";
vi.mocked(tenantBootstrap.isExactOwnedTenantCreationReplay).mockResolvedValueOnce(true);
const request = new Request("https://app.example.com/new-account", {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: new URLSearchParams({ name: "Acme", csrf: "csrf-token", creationRequestKey }),
});
const response = (await action({ request, params: {}, context: {} } as unknown as ActionFunctionArgs)) as Response;
expect(response.status).toBe(302);
expect(tenantBootstrap.isExactOwnedTenantCreationReplay).toHaveBeenCalledWith({
userId: "user_1",
name: "Acme",
slug: undefined,
creationRequestKey,
});
expect(checkAuthRateLimitMock).toHaveBeenNthCalledWith(1, {
request,
action: "workspace-create-attempt",
identifier: "user_1",
limit: 30,
windowMs: 900_000,
});
expect(checkAuthRateLimitMock).toHaveBeenNthCalledWith(2, {
request,
action: "workspace-create-replay",
identifier: "user_1",
limit: 20,
windowMs: 900_000,
});
expect(tenantsApi.TenantsApi.create).toHaveBeenCalledOnce();
});
it("returns a clear conflict without replacing the submitted creation key when the slug loses a race", async () => {
const creationRequestKey = "d7077797-054b-497a-b1ce-8e4f36257a96";
vi.mocked(tenantsApi.TenantsApi.create).mockRejectedValueOnce(new TenantSlugCollisionErrorMock());
const request = new Request("https://app.example.com/new-account", {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: new URLSearchParams({ name: "Acme", slug: "chosen", csrf: "csrf-token", creationRequestKey }),
});
const response = (await action({ request, params: {}, context: {} } as unknown as ActionFunctionArgs)) as Response;
expect(response.status).toBe(409);
await expect(response.json()).resolves.toEqual({
error: "translated:app.tenants.create.errors.slugTaken",
creationRequestKey,
});
});
it("preserves the creation key after an ambiguous failure so an exact retry cannot create a second workspace", async () => {
const creationRequestKey = "d7077797-054b-497a-b1ce-8e4f36257a96";
const body = { name: "Acme", slug: "acme", csrf: "csrf-token", creationRequestKey };
vi.mocked(tenantBootstrap.isExactOwnedTenantCreationReplay).mockResolvedValueOnce(false).mockResolvedValueOnce(true);
vi.mocked(tenantsApi.TenantsApi.create)
.mockRejectedValueOnce(new Error("response lost after commit"))
.mockResolvedValueOnce({ tenant: { id: "tenant_1", slug: "acme" }, user: { id: "user_1" } } as never);
const first = (await action({
request: new Request("https://app.example.com/new-account", {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: new URLSearchParams(body),
}),
params: {},
context: {},
} as unknown as ActionFunctionArgs)) as Response;
const retry = (await action({
request: new Request("https://app.example.com/new-account", {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: new URLSearchParams(body),
}),
params: {},
context: {},
} as unknown as ActionFunctionArgs)) as Response;
expect(first.status).toBe(400);
await expect(first.json()).resolves.toEqual({ error: "translated:app.tenants.create.errors.failed", creationRequestKey });
expect(retry.status).toBe(302);
expect(vi.mocked(tenantsApi.TenantsApi.create).mock.calls.map(([input]) => input.creationRequestKey)).toEqual([creationRequestKey, creationRequestKey]);
expect(checkAuthRateLimitMock.mock.calls.map(([input]) => input.action)).toEqual([
"workspace-create-attempt",
"workspace-create",
"workspace-create-attempt",
"workspace-create-replay",
]);
});
it("does not create a tenant when CSRF validation fails", async () => {
vi.mocked(sessionServer.validateCSRFToken).mockRejectedValueOnce(new Error("Invalid CSRF token"));
const response = (await action({
request: new Request("https://app.example.com/new-account", {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: new URLSearchParams({ name: "Acme" }),
}),
params: {},
context: {},
} as unknown as ActionFunctionArgs)) as Response;
expect(response.status).toBe(400);
await expect(response.json()).resolves.toEqual({ error: "translated:app.tenants.create.errors.failed" });
expect(tenantsApi.TenantsApi.create).not.toHaveBeenCalled();
});
});