Critical (data integrity):
- warehouse inventory confirm: throw (not return) inside $transaction so a
failed deficit line rolls back the surplus corrective receipt — retries
no longer accumulate phantom stock
- warehouse issue confirm: validate batches against the COMBINED quantity
of all lines (duplicate FIFO-resolved lines drove batches negative)
- attendance delete: restore vacation_used/sick_used for the deleted day
(in-transaction, clamped at 0)
High:
- auth refresh: terminated sessions (replaced_at only) get a plain 401 —
the theft branch (family revocation) now fires only on replaced_by_hash
- POST /users strips role_id for non-admin callers (mirrors PUT guard)
- issued-order transition flushes unsaved edits via the full save payload
when dirty; server contract (items+status in one PUT) pinned
- received-invoices list: usePaginatedQuery + pager (rows 26+ unreachable)
- received-invoice dates: nullableIsoDateString + NaN guard before NAS save
(Czech-format dates corrupted month/year, orphaned NAS files)
- leave approval skips Czech public holidays and books each calendar year's
hours against its own balance (mirrors createLeave)
Medium/Low (classes):
- 52 Zod caps aligned to DB column widths across 7 schemas (over-cap input
500ed at Prisma instead of a Czech 400)
- FK pre-validation: projects update + warehouse receipts/issues return
Czech 400s instead of P2003 500s
- invoice PDF degrades gracefully when the CNB rate is unavailable
(recap omitted instead of 500 + lost NAS archival)
- date boundaries: local-day filters (warehouse lists/reports, audit-log),
@db.Date coercion on invoice dates
- plan updateEntry re-checks the per-cell cap (self-excluding)
- {id} tiebreaks on customers/received-invoices/warehouse-items sorts;
/items honors the client sort param
- htmlToPdf relaunches once when the shared browser died mid-render
- offer number release parses the year from the document number (cross-year
finalize+delete left permanent sequence gaps)
- trips/vehicles km fields integer-coerced; AI budget regated to
settings.company|settings.system; Settings System tab no longer clobbers
Firma numbering patterns; draft invoices hide the dead PDF button;
dashboard quick-trip invalidates ["vehicles"]; TOTP secret cap 64;
audit-log + invoice month buckets day-shift fixes
Docs: corrected the stale "Chromium has no CSS margin-box footers" claim
(html-to-pdf.ts + CLAUDE.md — margin boxes render since Chrome 131); audit
report M3 withdrawn accordingly.
~65 new pinning tests; every finding reproduced RED against the real test
DB before its fix. Suite: 58 files / 634 tests green.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
138 lines
4.1 KiB
TypeScript
138 lines
4.1 KiB
TypeScript
import { describe, it, expect, beforeAll, afterAll } from "vitest";
|
|
import Fastify from "fastify";
|
|
import cookie from "@fastify/cookie";
|
|
import rateLimit from "@fastify/rate-limit";
|
|
import jwt from "jsonwebtoken";
|
|
import prisma from "../config/database";
|
|
import { config } from "../config/env";
|
|
import { securityHeaders } from "../middleware/security";
|
|
import aiRoutes from "../routes/admin/ai";
|
|
import { getBudgetUsd, setBudgetUsd } from "../services/ai.service";
|
|
|
|
/**
|
|
* Pinning test for audit finding L8a: the company-wide AI monthly budget must
|
|
* NOT be mutable by an ordinary ai.use holder (budget_usd=0 is a company-wide
|
|
* AI DoS; a huge value removes the cost cap). It is a company setting —
|
|
* settings.company / settings.system / admin only.
|
|
*/
|
|
|
|
const N = "ai_budget_perm_";
|
|
const stamp = Date.now().toString(36);
|
|
|
|
let app: ReturnType<typeof Fastify>;
|
|
let adminToken: string;
|
|
let aiUserToken: string;
|
|
let aiRoleId: number;
|
|
let savedBudget: number;
|
|
|
|
function token(user: { id: number; username: string; roleName: string }) {
|
|
return jwt.sign(
|
|
{ sub: user.id, username: user.username, role: user.roleName },
|
|
config.jwt.secret,
|
|
{ expiresIn: "15m" },
|
|
);
|
|
}
|
|
|
|
async function cleanup() {
|
|
await prisma.users.deleteMany({ where: { username: { startsWith: N } } });
|
|
const roles = await prisma.roles.findMany({
|
|
where: { name: { startsWith: N } },
|
|
select: { id: true },
|
|
});
|
|
const roleIds = roles.map((r) => r.id);
|
|
if (roleIds.length > 0) {
|
|
await prisma.role_permissions.deleteMany({
|
|
where: { role_id: { in: roleIds } },
|
|
});
|
|
await prisma.roles.deleteMany({ where: { id: { in: roleIds } } });
|
|
}
|
|
}
|
|
|
|
beforeAll(async () => {
|
|
await cleanup();
|
|
savedBudget = await getBudgetUsd();
|
|
|
|
app = Fastify({ logger: false });
|
|
await app.register(cookie);
|
|
await app.register(rateLimit, { max: 1000, timeWindow: "1 minute" });
|
|
app.addHook("onRequest", securityHeaders);
|
|
await app.register(aiRoutes, { prefix: "/api/admin/ai" });
|
|
|
|
const admin = await prisma.users.findFirst({
|
|
where: { roles: { name: "admin" } },
|
|
});
|
|
if (!admin) throw new Error("Test setup: admin user not found");
|
|
adminToken = token({
|
|
id: admin.id,
|
|
username: admin.username,
|
|
roleName: "admin",
|
|
});
|
|
|
|
// Ordinary ai.use holder — may chat, must NOT control the budget.
|
|
const role = await prisma.roles.create({
|
|
data: { name: `${N}aiuse_${stamp}`, display_name: "AI Use Only" },
|
|
});
|
|
aiRoleId = role.id;
|
|
const perm = await prisma.permissions.findFirst({
|
|
where: { name: "ai.use" },
|
|
});
|
|
if (!perm) throw new Error("Test setup: ai.use permission missing");
|
|
await prisma.role_permissions.create({
|
|
data: { role_id: aiRoleId, permission_id: perm.id },
|
|
});
|
|
const user = await prisma.users.create({
|
|
data: {
|
|
username: `${N}user_${stamp}`,
|
|
email: `${N}${stamp}@test.local`,
|
|
password_hash:
|
|
"$2a$10$invalidinvalidinvalidinvalidinvalidinvalidinvalidinvali",
|
|
first_name: "AiUse",
|
|
last_name: "Only",
|
|
is_active: true,
|
|
role_id: aiRoleId,
|
|
},
|
|
});
|
|
aiUserToken = token({
|
|
id: user.id,
|
|
username: user.username,
|
|
roleName: role.name,
|
|
});
|
|
});
|
|
|
|
afterAll(async () => {
|
|
await setBudgetUsd(savedBudget); // restore whatever the test DB had
|
|
if (app) await app.close();
|
|
await cleanup();
|
|
await prisma.$disconnect();
|
|
});
|
|
|
|
describe("PUT /ai/budget permission gate (audit L8a)", () => {
|
|
it("rejects an ordinary ai.use holder with 403", async () => {
|
|
const res = await app.inject({
|
|
method: "PUT",
|
|
url: "/api/admin/ai/budget",
|
|
headers: {
|
|
Authorization: `Bearer ${aiUserToken}`,
|
|
"Content-Type": "application/json",
|
|
},
|
|
payload: { budget_usd: 0 },
|
|
});
|
|
expect(res.statusCode).toBe(403);
|
|
// ...and the budget must be untouched.
|
|
expect(await getBudgetUsd()).toBe(savedBudget);
|
|
});
|
|
|
|
it("allows an admin to set the budget", async () => {
|
|
const res = await app.inject({
|
|
method: "PUT",
|
|
url: "/api/admin/ai/budget",
|
|
headers: {
|
|
Authorization: `Bearer ${adminToken}`,
|
|
"Content-Type": "application/json",
|
|
},
|
|
payload: { budget_usd: savedBudget },
|
|
});
|
|
expect(res.statusCode).toBe(200);
|
|
});
|
|
});
|