mirror of
https://github.com/snapotter-hq/SnapOtter.git
synced 2026-08-03 07:46:42 +02:00
test: coverage campaign and mutation testing across five packages (#628)
Coverage 83.6 to 87.36% lines, 81.63 to 84.14% branches. Mutation testing across five packages: image-engine 85, media-engine 92, doc-engine 87, shared+enterprise 86, apps/api security and jobs slice. Runs all five lanes weekly. Fixes the silently-broken mutation CI (babel pin), a redact-pdf envelope-shape test bug, an untested enterprise license valid-signature path, and an audit test that only exercised a hand-copied reproduction. Test and config only, no product code changes beyond the babel pin and one test-only oidc export. Full suite: 16,712 pass, 0 fail.
This commit is contained in:
@@ -1,3 +1,4 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { eq } from "drizzle-orm";
|
||||
import * as OTPAuth from "otpauth";
|
||||
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
|
||||
@@ -6,8 +7,11 @@ vi.resetModules();
|
||||
const { mockEnterpriseFeatures } = await import("../../helpers/enterprise-mock.js");
|
||||
mockEnterpriseFeatures(["mfa"]);
|
||||
|
||||
const { buildTestApp, loginAsAdmin, loginAsUser } = await import("../test-server.js");
|
||||
const { buildTestApp, loginAsAdmin, loginAsUser, createUserAndLogin } = await import(
|
||||
"../test-server.js"
|
||||
);
|
||||
const { db, schema } = await import("../../../apps/api/src/db/index.js");
|
||||
const { sharedRedis } = await import("../../../apps/api/src/jobs/connection.js");
|
||||
|
||||
import type { TestApp } from "../test-server.js";
|
||||
|
||||
@@ -208,6 +212,44 @@ describe("POST /api/auth/mfa/verify", () => {
|
||||
const [dbUser] = await db.select().from(schema.users).where(eq(schema.users.username, "admin"));
|
||||
expect(dbUser.totpEnabled).toBe(true);
|
||||
});
|
||||
|
||||
it("returns 400 NO_PENDING_ENROLLMENT when no enrollment was started", async () => {
|
||||
// State was cleared by afterEach, so there is no pending totpSecret.
|
||||
const res = await testApp.app.inject({
|
||||
method: "POST",
|
||||
url: "/api/auth/mfa/verify",
|
||||
headers: { authorization: `Bearer ${adminToken}` },
|
||||
payload: { code: "123456" },
|
||||
});
|
||||
expect(res.statusCode).toBe(400);
|
||||
expect(JSON.parse(res.body).code).toBe("NO_PENDING_ENROLLMENT");
|
||||
});
|
||||
|
||||
it("returns 409 MFA_ALREADY_ENABLED when MFA is already active", async () => {
|
||||
const enrollRes = await testApp.app.inject({
|
||||
method: "POST",
|
||||
url: "/api/auth/mfa/enroll",
|
||||
headers: { authorization: `Bearer ${adminToken}` },
|
||||
});
|
||||
const { uri } = JSON.parse(enrollRes.body);
|
||||
const code = generateTotpCode(uri);
|
||||
await testApp.app.inject({
|
||||
method: "POST",
|
||||
url: "/api/auth/mfa/verify",
|
||||
headers: { authorization: `Bearer ${adminToken}` },
|
||||
payload: { code },
|
||||
});
|
||||
|
||||
// Second verify against an already-active enrollment is a conflict.
|
||||
const res = await testApp.app.inject({
|
||||
method: "POST",
|
||||
url: "/api/auth/mfa/verify",
|
||||
headers: { authorization: `Bearer ${adminToken}` },
|
||||
payload: { code: generateTotpCode(uri) },
|
||||
});
|
||||
expect(res.statusCode).toBe(409);
|
||||
expect(JSON.parse(res.body).code).toBe("MFA_ALREADY_ENABLED");
|
||||
});
|
||||
});
|
||||
|
||||
describe("POST /api/auth/mfa/disable", () => {
|
||||
@@ -233,6 +275,71 @@ describe("POST /api/auth/mfa/disable", () => {
|
||||
});
|
||||
expect(res.statusCode).toBe(400);
|
||||
});
|
||||
|
||||
it("returns 400 MFA_NOT_ENABLED when MFA was never activated", async () => {
|
||||
// afterEach clears state, so totpEnabled is false here.
|
||||
const res = await testApp.app.inject({
|
||||
method: "POST",
|
||||
url: "/api/auth/mfa/disable",
|
||||
headers: { authorization: `Bearer ${adminToken}` },
|
||||
payload: { code: "123456" },
|
||||
});
|
||||
expect(res.statusCode).toBe(400);
|
||||
expect(JSON.parse(res.body).code).toBe("MFA_NOT_ENABLED");
|
||||
});
|
||||
|
||||
it("returns 401 INVALID_CODE when the TOTP code is wrong", async () => {
|
||||
const enrollRes = await testApp.app.inject({
|
||||
method: "POST",
|
||||
url: "/api/auth/mfa/enroll",
|
||||
headers: { authorization: `Bearer ${adminToken}` },
|
||||
});
|
||||
const { uri } = JSON.parse(enrollRes.body);
|
||||
await testApp.app.inject({
|
||||
method: "POST",
|
||||
url: "/api/auth/mfa/verify",
|
||||
headers: { authorization: `Bearer ${adminToken}` },
|
||||
payload: { code: generateTotpCode(uri) },
|
||||
});
|
||||
|
||||
const res = await testApp.app.inject({
|
||||
method: "POST",
|
||||
url: "/api/auth/mfa/disable",
|
||||
headers: { authorization: `Bearer ${adminToken}` },
|
||||
payload: { code: "000000" },
|
||||
});
|
||||
expect(res.statusCode).toBe(401);
|
||||
expect(JSON.parse(res.body).code).toBe("INVALID_CODE");
|
||||
});
|
||||
|
||||
it("clears all MFA data on success with a valid TOTP code", async () => {
|
||||
const enrollRes = await testApp.app.inject({
|
||||
method: "POST",
|
||||
url: "/api/auth/mfa/enroll",
|
||||
headers: { authorization: `Bearer ${adminToken}` },
|
||||
});
|
||||
const { uri } = JSON.parse(enrollRes.body);
|
||||
await testApp.app.inject({
|
||||
method: "POST",
|
||||
url: "/api/auth/mfa/verify",
|
||||
headers: { authorization: `Bearer ${adminToken}` },
|
||||
payload: { code: generateTotpCode(uri) },
|
||||
});
|
||||
|
||||
const res = await testApp.app.inject({
|
||||
method: "POST",
|
||||
url: "/api/auth/mfa/disable",
|
||||
headers: { authorization: `Bearer ${adminToken}` },
|
||||
payload: { code: generateTotpCode(uri) },
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(JSON.parse(res.body).ok).toBe(true);
|
||||
|
||||
const [dbUser] = await db.select().from(schema.users).where(eq(schema.users.username, "admin"));
|
||||
expect(dbUser.totpEnabled).toBe(false);
|
||||
expect(dbUser.totpSecret).toBeNull();
|
||||
expect(dbUser.recoveryCodesHash).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("POST /api/auth/users/:id/mfa/reset", () => {
|
||||
@@ -272,6 +379,97 @@ describe("POST /api/auth/users/:id/mfa/reset", () => {
|
||||
});
|
||||
expect(res.statusCode).toBe(403);
|
||||
});
|
||||
|
||||
it("returns 404 NOT_FOUND for an unknown target user", async () => {
|
||||
const res = await testApp.app.inject({
|
||||
method: "POST",
|
||||
url: `/api/auth/users/${randomUUID()}/mfa/reset`,
|
||||
headers: { authorization: `Bearer ${adminToken}` },
|
||||
});
|
||||
expect(res.statusCode).toBe(404);
|
||||
expect(JSON.parse(res.body).code).toBe("NOT_FOUND");
|
||||
});
|
||||
|
||||
it("returns 400 MFA_NOT_ENABLED when the target has no MFA", async () => {
|
||||
const { userId } = await createUserAndLogin(testApp.app, "mfa_reset_no_mfa_user", "user");
|
||||
|
||||
const res = await testApp.app.inject({
|
||||
method: "POST",
|
||||
url: `/api/auth/users/${userId}/mfa/reset`,
|
||||
headers: { authorization: `Bearer ${adminToken}` },
|
||||
});
|
||||
expect(res.statusCode).toBe(400);
|
||||
expect(JSON.parse(res.body).code).toBe("MFA_NOT_ENABLED");
|
||||
|
||||
await db.delete(schema.users).where(eq(schema.users.id, userId));
|
||||
});
|
||||
|
||||
it("returns 403 ESCALATION_DENIED when a scoped admin key can't manage the target role", async () => {
|
||||
// A second admin is the target. The actor is the built-in admin, but acting
|
||||
// through an API key scoped to ONLY users:manage: it passes the route's
|
||||
// permission gate yet lacks the full admin permission set, so it cannot
|
||||
// manage another admin. This is the real authority-boundary path (#618).
|
||||
const { userId: targetAdminId } = await createUserAndLogin(
|
||||
testApp.app,
|
||||
"mfa_reset_target_admin",
|
||||
"admin",
|
||||
);
|
||||
|
||||
const keyRes = await testApp.app.inject({
|
||||
method: "POST",
|
||||
url: "/api/v1/api-keys",
|
||||
headers: { authorization: `Bearer ${adminToken}` },
|
||||
payload: { name: "scoped-users-manage", permissions: ["users:manage"] },
|
||||
});
|
||||
expect(keyRes.statusCode).toBe(201);
|
||||
const { key: scopedKey, id: scopedKeyId } = JSON.parse(keyRes.body);
|
||||
|
||||
const res = await testApp.app.inject({
|
||||
method: "POST",
|
||||
url: `/api/auth/users/${targetAdminId}/mfa/reset`,
|
||||
headers: { authorization: `Bearer ${scopedKey}` },
|
||||
});
|
||||
expect(res.statusCode).toBe(403);
|
||||
expect(JSON.parse(res.body).code).toBe("ESCALATION_DENIED");
|
||||
|
||||
// Delete the target admin (cascades its sessions) and the stray scoped key
|
||||
// so neither leaks into other suites sharing the fork DB.
|
||||
await db.delete(schema.users).where(eq(schema.users.id, targetAdminId));
|
||||
await db.delete(schema.apiKeys).where(eq(schema.apiKeys.id, scopedKeyId));
|
||||
});
|
||||
|
||||
it("clears MFA data for a target user on success", async () => {
|
||||
const username = "mfa_reset_target_user";
|
||||
const { userId, token: userToken } = await createUserAndLogin(testApp.app, username, "user");
|
||||
|
||||
const enrollRes = await testApp.app.inject({
|
||||
method: "POST",
|
||||
url: "/api/auth/mfa/enroll",
|
||||
headers: { authorization: `Bearer ${userToken}` },
|
||||
});
|
||||
const { uri } = JSON.parse(enrollRes.body);
|
||||
await testApp.app.inject({
|
||||
method: "POST",
|
||||
url: "/api/auth/mfa/verify",
|
||||
headers: { authorization: `Bearer ${userToken}` },
|
||||
payload: { code: generateTotpCode(uri) },
|
||||
});
|
||||
|
||||
const res = await testApp.app.inject({
|
||||
method: "POST",
|
||||
url: `/api/auth/users/${userId}/mfa/reset`,
|
||||
headers: { authorization: `Bearer ${adminToken}` },
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(JSON.parse(res.body).ok).toBe(true);
|
||||
|
||||
const [dbUser] = await db.select().from(schema.users).where(eq(schema.users.id, userId));
|
||||
expect(dbUser.totpEnabled).toBe(false);
|
||||
expect(dbUser.totpSecret).toBeNull();
|
||||
expect(dbUser.recoveryCodesHash).toBeNull();
|
||||
|
||||
await db.delete(schema.users).where(eq(schema.users.id, userId));
|
||||
});
|
||||
});
|
||||
|
||||
describe("GET /api/auth/session totpEnabled", () => {
|
||||
@@ -409,6 +607,171 @@ describe("MFA login flow", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("POST /api/auth/mfa/complete edge cases", () => {
|
||||
afterEach(async () => {
|
||||
await clearMfaState("admin");
|
||||
});
|
||||
|
||||
it("returns 400 VALIDATION_ERROR when mfaToken is not a uuid", async () => {
|
||||
const res = await testApp.app.inject({
|
||||
method: "POST",
|
||||
url: "/api/auth/mfa/complete",
|
||||
payload: { mfaToken: "not-a-uuid", code: "123456" },
|
||||
});
|
||||
expect(res.statusCode).toBe(400);
|
||||
expect(JSON.parse(res.body).code).toBe("VALIDATION_ERROR");
|
||||
});
|
||||
|
||||
it("returns 401 MFA_EXPIRED for an unknown challenge token", async () => {
|
||||
const res = await testApp.app.inject({
|
||||
method: "POST",
|
||||
url: "/api/auth/mfa/complete",
|
||||
// Valid uuid shape so it passes Zod, but no Redis entry backs it.
|
||||
payload: { mfaToken: randomUUID(), code: "123456" },
|
||||
});
|
||||
expect(res.statusCode).toBe(401);
|
||||
expect(JSON.parse(res.body).code).toBe("MFA_EXPIRED");
|
||||
});
|
||||
|
||||
it("returns 401 MFA_NOT_CONFIGURED when the challenged user has no TOTP secret", async () => {
|
||||
// A live challenge token whose user never finished enrollment (no secret).
|
||||
const [dbUser] = await db.select().from(schema.users).where(eq(schema.users.username, "admin"));
|
||||
const mfaToken = randomUUID();
|
||||
await sharedRedis().setex(`mfa:${mfaToken}`, 300, dbUser.id);
|
||||
|
||||
const res = await testApp.app.inject({
|
||||
method: "POST",
|
||||
url: "/api/auth/mfa/complete",
|
||||
payload: { mfaToken, code: "123456" },
|
||||
});
|
||||
expect(res.statusCode).toBe(401);
|
||||
expect(JSON.parse(res.body).code).toBe("MFA_NOT_CONFIGURED");
|
||||
await sharedRedis().del(`mfa:${mfaToken}`);
|
||||
});
|
||||
|
||||
it("returns 401 MFA_NOT_CONFIGURED when the challenged user's role is disabled", async () => {
|
||||
// Enroll + verify a disposable user so it has a real secret, then disable
|
||||
// its role. The disabled-role guard must reject even with a valid secret.
|
||||
const username = "mfa_disabled_complete_user";
|
||||
const { userId, token: userToken } = await createUserAndLogin(testApp.app, username, "user");
|
||||
|
||||
const enrollRes = await testApp.app.inject({
|
||||
method: "POST",
|
||||
url: "/api/auth/mfa/enroll",
|
||||
headers: { authorization: `Bearer ${userToken}` },
|
||||
});
|
||||
const { uri } = JSON.parse(enrollRes.body);
|
||||
await testApp.app.inject({
|
||||
method: "POST",
|
||||
url: "/api/auth/mfa/verify",
|
||||
headers: { authorization: `Bearer ${userToken}` },
|
||||
payload: { code: generateTotpCode(uri) },
|
||||
});
|
||||
|
||||
await db.update(schema.users).set({ role: "disabled" }).where(eq(schema.users.id, userId));
|
||||
|
||||
const mfaToken = randomUUID();
|
||||
await sharedRedis().setex(`mfa:${mfaToken}`, 300, userId);
|
||||
|
||||
const res = await testApp.app.inject({
|
||||
method: "POST",
|
||||
url: "/api/auth/mfa/complete",
|
||||
payload: { mfaToken, code: generateTotpCode(uri) },
|
||||
});
|
||||
expect(res.statusCode).toBe(401);
|
||||
expect(JSON.parse(res.body).code).toBe("MFA_NOT_CONFIGURED");
|
||||
|
||||
await sharedRedis().del(`mfa:${mfaToken}`);
|
||||
await db.delete(schema.users).where(eq(schema.users.id, userId));
|
||||
});
|
||||
|
||||
it("completes login with a recovery code and consumes it", async () => {
|
||||
const enrollRes = await testApp.app.inject({
|
||||
method: "POST",
|
||||
url: "/api/auth/mfa/enroll",
|
||||
headers: { authorization: `Bearer ${adminToken}` },
|
||||
});
|
||||
const { uri, recoveryCodes } = JSON.parse(enrollRes.body);
|
||||
await testApp.app.inject({
|
||||
method: "POST",
|
||||
url: "/api/auth/mfa/verify",
|
||||
headers: { authorization: `Bearer ${adminToken}` },
|
||||
payload: { code: generateTotpCode(uri) },
|
||||
});
|
||||
|
||||
const loginRes = await testApp.app.inject({
|
||||
method: "POST",
|
||||
url: "/api/auth/login",
|
||||
payload: { username: "admin", password: "Adminpass1" },
|
||||
});
|
||||
const { mfaToken } = JSON.parse(loginRes.body);
|
||||
|
||||
// Use a recovery code (not the TOTP) to complete: hits the recoveryUsed path.
|
||||
const recoveryCode = recoveryCodes[0];
|
||||
const res = await testApp.app.inject({
|
||||
method: "POST",
|
||||
url: "/api/auth/mfa/complete",
|
||||
payload: { mfaToken, code: recoveryCode },
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = JSON.parse(res.body);
|
||||
expect(body.token).toBeDefined();
|
||||
expect(body.user.username).toBe("admin");
|
||||
|
||||
// The recovery code was consumed: the stored hash list dropped one entry.
|
||||
const [dbUser] = await db.select().from(schema.users).where(eq(schema.users.username, "admin"));
|
||||
expect(dbUser.recoveryCodesHash).not.toBeNull();
|
||||
const remaining = (dbUser.recoveryCodesHash ?? "").split(",").filter(Boolean);
|
||||
expect(remaining).toHaveLength(recoveryCodes.length - 1);
|
||||
});
|
||||
|
||||
it("burns the last remaining recovery code to an empty stored list", async () => {
|
||||
// Enroll a fresh user, then overwrite its stored recovery hash with a
|
||||
// single known code so the consume path collapses to the empty-string
|
||||
// (`|| null`) branch.
|
||||
const username = "mfa_last_recovery_user";
|
||||
const { userId, token: userToken } = await createUserAndLogin(testApp.app, username, "user");
|
||||
|
||||
const enrollRes = await testApp.app.inject({
|
||||
method: "POST",
|
||||
url: "/api/auth/mfa/enroll",
|
||||
headers: { authorization: `Bearer ${userToken}` },
|
||||
});
|
||||
const { uri } = JSON.parse(enrollRes.body);
|
||||
await testApp.app.inject({
|
||||
method: "POST",
|
||||
url: "/api/auth/mfa/verify",
|
||||
headers: { authorization: `Bearer ${userToken}` },
|
||||
payload: { code: generateTotpCode(uri) },
|
||||
});
|
||||
|
||||
const { createHash } = await import("node:crypto");
|
||||
const singleCode = "lastcode";
|
||||
const singleHash = createHash("sha256").update(singleCode).digest("hex");
|
||||
await db
|
||||
.update(schema.users)
|
||||
.set({ recoveryCodesHash: singleHash })
|
||||
.where(eq(schema.users.id, userId));
|
||||
|
||||
const mfaToken = randomUUID();
|
||||
await sharedRedis().setex(`mfa:${mfaToken}`, 300, userId);
|
||||
|
||||
const res = await testApp.app.inject({
|
||||
method: "POST",
|
||||
url: "/api/auth/mfa/complete",
|
||||
payload: { mfaToken, code: singleCode },
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
|
||||
// Consuming the only code leaves an empty string -> stored as null.
|
||||
const [dbUser] = await db.select().from(schema.users).where(eq(schema.users.id, userId));
|
||||
expect(dbUser.recoveryCodesHash).toBeNull();
|
||||
|
||||
await sharedRedis().del(`mfa:${mfaToken}`);
|
||||
await db.delete(schema.users).where(eq(schema.users.id, userId));
|
||||
});
|
||||
});
|
||||
|
||||
async function setMfaPolicy(value: "optional" | "admins_only" | "required"): Promise<void> {
|
||||
await db
|
||||
.insert(schema.settings)
|
||||
|
||||
Reference in New Issue
Block a user