Files

140 lines
6.9 KiB
TypeScript

import { beforeEach, describe, expect, it, vi } from "vitest";
const mocks = vi.hoisted(() => ({
loadContext: vi.fn(),
requirePermission: vi.fn(),
validateCsrf: vi.fn(),
exportVault: vi.fn(),
reveal: vi.fn(),
copy: vi.fn(),
createVault: vi.fn(),
createEntry: vi.fn(),
updateEntry: vi.fn(),
archiveEntry: vi.fn(),
restoreEntry: vi.fn(),
grantAccess: vi.fn(),
revokeAccess: vi.fn(),
archiveVault: vi.fn(),
restoreVault: vi.fn(),
}));
vi.mock("~/utils/integrations/hrAccess.server", () => ({
loadHrContext: mocks.loadContext,
requireHrPermission: mocks.requirePermission,
badRequestResponse: () => new Response("Bad Request", { status: 400 }),
notFoundResponse: () => new Response("Not Found", { status: 404 }),
hrActionErrorResponse: (error: unknown) => {
throw error;
},
}));
vi.mock("~/utils/integrations/hrPasswordSafeService.server", () => ({
exportVault: mocks.exportVault,
revealEntryValue: mocks.reveal,
copyEntryValue: mocks.copy,
createVault: mocks.createVault,
createEntry: mocks.createEntry,
updateEntry: mocks.updateEntry,
archiveEntry: mocks.archiveEntry,
restoreEntry: mocks.restoreEntry,
grantAccess: mocks.grantAccess,
revokeAccess: mocks.revokeAccess,
archiveVault: mocks.archiveVault,
restoreVault: mocks.restoreVault,
}));
vi.mock("~/utils/session.server", () => ({ validateCSRFToken: mocks.validateCsrf }));
import { action as exportAction, loader as exportLoader } from "./app.$tenant/passwords.$vaultId.export";
import { action as revealAction, loader as revealLoader } from "./app.$tenant/passwords.$vaultId.reveal";
import { action as detailAction } from "./app.$tenant/passwords.$vaultId._index";
import { action as listAction } from "./app.$tenant/passwords._index";
import { action as adminAction } from "./app.$tenant/passwords.admin";
function actionArgs(path: string, body: URLSearchParams) {
return {
request: new Request(`https://app.example.test${path}`, { method: "POST", body }),
params: { tenant: "acme", vaultId: "vault-1" },
context: {},
} as never;
}
describe("password command routes", () => {
beforeEach(() => {
vi.clearAllMocks();
mocks.loadContext.mockResolvedValue({ tenantId: "tenant-1", userId: "user-1", permissions: [], hasModule: true });
mocks.validateCsrf.mockResolvedValue(undefined);
mocks.exportVault.mockResolvedValue({ vaultName: "Ops", entries: [] });
mocks.reveal.mockResolvedValue("revealed");
mocks.copy.mockResolvedValue("copied");
mocks.createVault.mockResolvedValue({ id: "vault-new" });
mocks.createEntry.mockResolvedValue({ id: "entry-new" });
mocks.updateEntry.mockResolvedValue(undefined);
mocks.archiveEntry.mockResolvedValue(undefined);
mocks.restoreEntry.mockResolvedValue(undefined);
mocks.grantAccess.mockResolvedValue(undefined);
mocks.revokeAccess.mockResolvedValue(undefined);
mocks.archiveVault.mockResolvedValue(undefined);
mocks.restoreVault.mockResolvedValue(undefined);
});
it("keeps export POST-only and requires use plus the separate export permission and confirmation", async () => {
expect(() => exportLoader()).toThrow(expect.objectContaining({ status: 404 }));
const response = await exportAction(actionArgs("/acme/passwords/vault-1/export", new URLSearchParams({ csrf: "token", confirm: "export" })));
expect(mocks.requirePermission.mock.calls.map((call) => call[1])).toEqual(["hr.passwordsafe.use", "hr.passwordsafe.export"]);
expect(mocks.validateCsrf).toHaveBeenCalledOnce();
expect(mocks.exportVault).toHaveBeenCalledWith({
tenantId: "tenant-1",
vaultId: "vault-1",
userId: "user-1",
hasExportPermission: true,
});
expect(response.headers.get("content-disposition")).toContain("password-safe-vault-1.json");
});
it("rejects export without an explicit confirmation", async () => {
await expect(exportAction(actionArgs("/acme/passwords/vault-1/export", new URLSearchParams({ csrf: "token" })))).rejects.toMatchObject({ status: 400 });
expect(mocks.exportVault).not.toHaveBeenCalled();
});
it("dispatches reveal and copy as distinct CSRF-protected commands", async () => {
expect(() => revealLoader()).toThrow(expect.objectContaining({ status: 404 }));
await revealAction(actionArgs("/acme/passwords/vault-1/reveal", new URLSearchParams({ csrf: "token", intent: "reveal", entryId: "entry-1", field: "password" })));
await revealAction(actionArgs("/acme/passwords/vault-1/reveal", new URLSearchParams({ csrf: "token", intent: "copy", entryId: "entry-1", field: "password" })));
expect(mocks.validateCsrf).toHaveBeenCalledTimes(2);
expect(mocks.reveal).toHaveBeenCalledOnce();
expect(mocks.copy).toHaveBeenCalledOnce();
});
it("keeps vault and entry mutations CSRF-protected and returns translated success states", async () => {
const createVaultResponse = await listAction(
actionArgs("/acme/passwords", new URLSearchParams({ csrf: "token", intent: "create-vault", name: "Ops", description: "Team" }))
);
expect(await createVaultResponse.json()).toMatchObject({ ok: true, messageKey: "hr.passwordSafe.feedback.vaultCreated" });
const detailCases = [
["create-entry", { title: "Router", username: "alice", password: "secret" }, mocks.createEntry, "hr.passwordSafe.feedback.entryCreated"],
["update-entry", { entryId: "entry-1", title: "Router neu" }, mocks.updateEntry, "hr.passwordSafe.feedback.entryUpdated"],
["archive-entry", { entryId: "entry-1" }, mocks.archiveEntry, "hr.passwordSafe.feedback.entryArchived"],
["restore-entry", { entryId: "entry-1" }, mocks.restoreEntry, "hr.passwordSafe.feedback.entryRestored"],
["grant-access", { targetUserId: "member-1", permissionLevel: "write" }, mocks.grantAccess, "hr.passwordSafe.feedback.accessGranted"],
["revoke-access", { targetUserId: "member-1" }, mocks.revokeAccess, "hr.passwordSafe.feedback.accessRevoked"],
] as const;
for (const [intent, values, command, messageKey] of detailCases) {
const response = await detailAction(
actionArgs(`/acme/passwords/vault-1`, new URLSearchParams({ csrf: "token", intent, ...values }))
);
expect(command).toHaveBeenCalled();
expect(await response.json()).toMatchObject({ ok: true, messageKey });
}
const archiveResponse = await adminAction(
actionArgs("/acme/passwords/admin", new URLSearchParams({ csrf: "token", intent: "archive-vault", vaultId: "vault-1" }))
);
const restoreResponse = await adminAction(
actionArgs("/acme/passwords/admin", new URLSearchParams({ csrf: "token", intent: "restore-vault", vaultId: "vault-1" }))
);
expect(await archiveResponse.json()).toMatchObject({ ok: true, messageKey: "hr.passwordSafe.feedback.vaultArchived" });
expect(await restoreResponse.json()).toMatchObject({ ok: true, messageKey: "hr.passwordSafe.feedback.vaultRestored" });
expect(mocks.validateCsrf).toHaveBeenCalledTimes(9);
});
});