import { afterAll, beforeAll, describe, expect, it } from "vitest"; import type { Envelope, Transport, TransportMakeRequestResponse } from "@sentry/core"; import type { ErrorEvent } from "@sentry/node"; import type { FastifyInstance } from "fastify"; import { buildApp } from "../src/app.ts"; import { flushSentry, initSentry, scrubEvent } from "../src/sentry.ts"; /** Мок транспорта Sentry: собирает конверты вместо отправки в Bugsink. */ const mockSentryEnvelopes: Envelope[] = []; function mockSentryTransport(): Transport { return { send(envelope: Envelope): PromiseLike { mockSentryEnvelopes.push(envelope); return Promise.resolve({ statusCode: 200 }); }, flush: () => Promise.resolve(true), }; } function sentEvents(): Record[] { return mockSentryEnvelopes.flatMap((env) => env[1] .filter(([header]) => header.type === "event") .map(([, payload]) => payload as Record), ); } describe("Requirement: Отчёт об ошибках в Bugsink", () => { it("Scenario: DSN не задан", async () => { expect(initSentry({})).toBe(false); const app = await buildApp(); const res = await app.inject({ method: "GET", url: "/healthz" }); expect(res.statusCode).toBe(200); await flushSentry(); expect(mockSentryEnvelopes).toHaveLength(0); await app.close(); }); describe("с DSN", () => { let app: FastifyInstance; beforeAll(async () => { initSentry( { SENTRY_DSN: "https://mockpublickey@mock-bugsink.invalid/1", SENTRY_ENVIRONMENT: "staging", SENTRY_RELEASE: "abc123", }, { transport: mockSentryTransport, defaultIntegrations: false }, ); app = await buildApp(); app.get("/boom", async () => { throw new Error("boom for bugsink"); }); }); afterAll(async () => app.close()); it("Scenario: Ошибка уходит в Bugsink без ПДн", async () => { const res = await app.inject({ method: "GET", url: "/boom?email=anna@example.com", headers: { cookie: "session=mock-session-cookie", authorization: "Bearer mock-token", "x-forwarded-for": "203.0.113.7", }, remoteAddress: "203.0.113.7", }); expect(res.statusCode).toBe(500); await flushSentry(); const events = sentEvents(); expect(events).toHaveLength(1); const event = events[0]; expect(event?.environment).toBe("staging"); expect(event?.release).toBe("abc123"); const raw = JSON.stringify(event); expect(raw).toContain("boom for bugsink"); for (const leak of ["203.0.113.7", "mock-session-cookie", "mock-token", "anna@example.com"]) { expect(raw).not.toContain(leak); } }); }); }); describe("scrubEvent", () => { it("удаляет IP, cookies, заголовки авторизации и query", () => { const event = { type: undefined, user: { ip_address: "203.0.113.7", id: "u1" }, request: { url: "https://x.test/a?token=1", query_string: "token=1", cookies: { s: "1" }, data: { password: "p" }, headers: { Cookie: "s=1", Authorization: "Bearer t", "X-Forwarded-For": "1.2.3.4", Accept: "*/*" }, }, } as unknown as ErrorEvent; const out = scrubEvent(event); expect(out.user).toEqual({ id: "u1" }); expect(out.request).toEqual({ url: "https://x.test/a", headers: { Accept: "*/*" } }); }); });