223 行
8.3 KiB
JavaScript
223 行
8.3 KiB
JavaScript
const fs = require("node:fs/promises");
|
|
const os = require("node:os");
|
|
const path = require("node:path");
|
|
|
|
const Fastify = require("fastify");
|
|
|
|
const { AppError } = require("../../../src/utils/AppError");
|
|
const { registerInvoicePoolReadRoutes } = require("../../../src/routes/invoicePool/read");
|
|
const { signPayload, verifyToken } = require("../../../src/utils/signedUrl");
|
|
|
|
const INVOICE_ID = "11111111-1111-4111-8111-111111111111";
|
|
const ACTOR_ID = "22222222-2222-4222-8222-222222222222";
|
|
const JWT_SECRET = "synthetic-test-secret";
|
|
|
|
async function buildApp({ auditFailure = null, invoiceOverrides = {}, employee = null, pendingTask = null } = {}) {
|
|
const storageDir = await fs.mkdtemp(path.join(os.tmpdir(), "hyb-oa-invoice-file-"));
|
|
const fileContents = "%PDF synthetic\n%%EOF\n";
|
|
await fs.writeFile(path.join(storageDir, "invoice.pdf"), fileContents);
|
|
|
|
const prisma = {
|
|
invoicePool: {
|
|
findUnique: vi.fn().mockResolvedValue({
|
|
id: INVOICE_ID,
|
|
owner_employee_id: ACTOR_ID,
|
|
uploaded_by_employee_id: ACTOR_ID,
|
|
linked_reimbursement_id: null,
|
|
linked_reimbursement: null,
|
|
storage_path: "invoice.pdf",
|
|
mime_type: "application/pdf",
|
|
original_name: "住宿电子普通发票.pdf",
|
|
file_size: Buffer.byteLength(fileContents),
|
|
...invoiceOverrides,
|
|
}),
|
|
},
|
|
workflowTask: {
|
|
findFirst: vi.fn().mockResolvedValue(pendingTask),
|
|
},
|
|
auditLog: {
|
|
create: auditFailure
|
|
? vi.fn().mockRejectedValue(auditFailure)
|
|
: vi.fn().mockResolvedValue({ id: "audit-1" }),
|
|
},
|
|
};
|
|
|
|
const app = Fastify();
|
|
app.decorate("prisma", prisma);
|
|
app.decorate("config", {
|
|
jwtSecret: JWT_SECRET,
|
|
storageDir,
|
|
appOrigin: "https://oa.hyinda.com",
|
|
signedUrlTtlSeconds: 600,
|
|
});
|
|
app.decorate("authenticate", async (request) => {
|
|
if (!request.headers.authorization) {
|
|
throw new AppError({ code: "AUTH_001", message: "未登录", statusCode: 401 });
|
|
}
|
|
request.employee = employee ?? {
|
|
id: ACTOR_ID,
|
|
roleCodes: ["finance"],
|
|
permissionCodes: [],
|
|
};
|
|
});
|
|
app.decorate("hasPermission", () => false);
|
|
app.decorate("requirePermission", () => async () => {});
|
|
app.setErrorHandler((error, request, reply) => {
|
|
if (error instanceof AppError) {
|
|
return reply.status(error.statusCode).send({
|
|
requestId: request.id,
|
|
error: { code: error.code, message: error.message, details: error.details ?? {} },
|
|
});
|
|
}
|
|
return reply.status(500).send({
|
|
requestId: request.id,
|
|
error: { code: "SYS_001", message: "服务器内部错误", details: {} },
|
|
});
|
|
});
|
|
await app.register(registerInvoicePoolReadRoutes, { prefix: "/api" });
|
|
return { app, prisma, storageDir, fileContents };
|
|
}
|
|
|
|
describe("GET /api/invoice-pool/:id/file", () => {
|
|
it("returns a Chinese PDF name through a safe inline Content-Disposition", async () => {
|
|
const { app, prisma, storageDir } = await buildApp();
|
|
const exp = Date.now() + 60_000;
|
|
const token = signPayload({ invoiceId: INVOICE_ID, actorId: ACTOR_ID, exp }, JWT_SECRET);
|
|
|
|
try {
|
|
const response = await app.inject({
|
|
method: "GET",
|
|
url: `/api/invoice-pool/${INVOICE_ID}/file?token=${encodeURIComponent(token)}`,
|
|
});
|
|
|
|
expect(response.statusCode).toBe(200);
|
|
expect(response.headers["content-type"]).toContain("application/pdf");
|
|
expect(response.headers["content-disposition"]).toBe(
|
|
"inline; filename=\"attachment.pdf\"; filename*=UTF-8''%E4%BD%8F%E5%AE%BF%E7%94%B5%E5%AD%90%E6%99%AE%E9%80%9A%E5%8F%91%E7%A5%A8.pdf",
|
|
);
|
|
expect(response.headers["content-disposition"]).not.toContain("住宿电子普通发票");
|
|
expect(prisma.auditLog.create).toHaveBeenCalledWith(
|
|
expect.objectContaining({ data: expect.objectContaining({ action: "INVOICE_FILE_DOWNLOADED" }) }),
|
|
);
|
|
} finally {
|
|
await app.close();
|
|
await fs.rm(storageDir, { recursive: true, force: true });
|
|
}
|
|
});
|
|
|
|
it("fails closed when the file access audit cannot be written", async () => {
|
|
const { app, storageDir } = await buildApp({ auditFailure: new Error("synthetic audit outage") });
|
|
const exp = Date.now() + 60_000;
|
|
const token = signPayload({ invoiceId: INVOICE_ID, actorId: ACTOR_ID, exp }, JWT_SECRET);
|
|
|
|
try {
|
|
const response = await app.inject({
|
|
method: "GET",
|
|
url: `/api/invoice-pool/${INVOICE_ID}/file?token=${encodeURIComponent(token)}`,
|
|
});
|
|
|
|
expect(response.statusCode).toBe(500);
|
|
expect(response.json().error.code).toBe("SYS_001");
|
|
expect(response.body).not.toContain("%PDF synthetic");
|
|
} finally {
|
|
await app.close();
|
|
await fs.rm(storageDir, { recursive: true, force: true });
|
|
}
|
|
});
|
|
});
|
|
|
|
describe("POST /api/invoice-pool/:id/signed-url", () => {
|
|
it("issues an object-bound URL for at most 120 seconds with preview metadata", async () => {
|
|
const { app, prisma, storageDir, fileContents } = await buildApp();
|
|
const issuedBefore = Date.now();
|
|
|
|
try {
|
|
const response = await app.inject({
|
|
method: "POST",
|
|
url: `/api/invoice-pool/${INVOICE_ID}/signed-url`,
|
|
headers: { authorization: "Bearer test", "content-type": "application/json" },
|
|
payload: {},
|
|
});
|
|
|
|
expect(response.statusCode).toBe(200);
|
|
expect(response.json().data).toEqual(expect.objectContaining({
|
|
signedUrl: expect.stringMatching(/^https:\/\/oa\.hyinda\.com\/api\/invoice-pool\//),
|
|
originalName: "住宿电子普通发票.pdf",
|
|
mimeType: "application/pdf",
|
|
fileSize: Buffer.byteLength(fileContents),
|
|
}));
|
|
const url = new URL(response.json().data.signedUrl);
|
|
const verified = verifyToken(url.searchParams.get("token"), JWT_SECRET);
|
|
expect(verified).toEqual(expect.objectContaining({
|
|
ok: true,
|
|
payload: expect.objectContaining({ invoiceId: INVOICE_ID, actorId: ACTOR_ID }),
|
|
}));
|
|
expect(verified.payload.exp).toBeGreaterThanOrEqual(issuedBefore + 119_000);
|
|
expect(verified.payload.exp).toBeLessThanOrEqual(Date.now() + 120_000);
|
|
expect(prisma.auditLog.create).toHaveBeenCalledWith(expect.objectContaining({
|
|
data: expect.objectContaining({
|
|
action: "INVOICE_SIGNED_URL_ISSUED",
|
|
actor_id: ACTOR_ID,
|
|
target_id: INVOICE_ID,
|
|
}),
|
|
}));
|
|
} finally {
|
|
await app.close();
|
|
await fs.rm(storageDir, { recursive: true, force: true });
|
|
}
|
|
});
|
|
|
|
it("requires authentication before issuing a signed URL", async () => {
|
|
const { app, prisma, storageDir } = await buildApp();
|
|
|
|
try {
|
|
const response = await app.inject({
|
|
method: "POST",
|
|
url: `/api/invoice-pool/${INVOICE_ID}/signed-url`,
|
|
payload: {},
|
|
});
|
|
|
|
expect(response.statusCode).toBe(401);
|
|
expect(prisma.invoicePool.findUnique).not.toHaveBeenCalled();
|
|
} finally {
|
|
await app.close();
|
|
await fs.rm(storageDir, { recursive: true, force: true });
|
|
}
|
|
});
|
|
|
|
it("allows the current pending approver without granting invoice management permission", async () => {
|
|
const approverId = "33333333-3333-4333-8333-333333333333";
|
|
const linkedReimbursementId = "44444444-4444-4444-8444-444444444444";
|
|
const { app, prisma, storageDir } = await buildApp({
|
|
employee: { id: approverId, roleCodes: ["manager"], permissionCodes: [] },
|
|
invoiceOverrides: {
|
|
owner_employee_id: ACTOR_ID,
|
|
uploaded_by_employee_id: ACTOR_ID,
|
|
linked_reimbursement_id: linkedReimbursementId,
|
|
linked_reimbursement: { owner_id: ACTOR_ID, submitter_id: ACTOR_ID },
|
|
},
|
|
pendingTask: { id: "synthetic-pending-task" },
|
|
});
|
|
|
|
try {
|
|
const response = await app.inject({
|
|
method: "POST",
|
|
url: `/api/invoice-pool/${INVOICE_ID}/signed-url`,
|
|
headers: { authorization: "Bearer test", "content-type": "application/json" },
|
|
payload: {},
|
|
});
|
|
|
|
expect(response.statusCode).toBe(200);
|
|
expect(prisma.workflowTask.findFirst).toHaveBeenCalledWith(expect.objectContaining({
|
|
where: expect.objectContaining({ status: "pending" }),
|
|
}));
|
|
expect(prisma.auditLog.create).toHaveBeenCalledWith(expect.objectContaining({
|
|
data: expect.objectContaining({ actor_id: approverId, action: "INVOICE_SIGNED_URL_ISSUED" }),
|
|
}));
|
|
} finally {
|
|
await app.close();
|
|
await fs.rm(storageDir, { recursive: true, force: true });
|
|
}
|
|
});
|
|
});
|