Files
paula-alves 2ec4f263b6
ci / typescript (push) Skipped
ci / rust (push) Skipped
ci / rust (pull_request) Successful in 4m33s
ci / typescript (pull_request) Successful in 11m56s
Stop the health-check error loop on Postgres connection exhaustion (BIT-33548)
The /health endpoint ran db.$queryRaw`SELECT 1` with no error handling.
When PostgreSQL hits max_connections (error 53300), the query threw
PrismaClientKnownRequestError, the error handler logged it as 'unhandled
error', and the reporter sent it to errors.bitreport.pt — creating an
error loop of one-off incidents from every health check.

Two fixes:
- /health now catches DB failures and returns 503 { status: 'degraded' }
  instead of throwing, so a connection-starved health check degrades
  gracefully rather than generating an error report.
- isTransientDatabaseError now filters 53300 (pool exhaustion) alongside
  the existing 57P01/57P03/P1001/P1017 filters, so even if a 53300 surfaces
  through another code path it does not trip the error loop.

Paperclip-Issue: BIT-33548
2026-12-04 07:31:32 +00:00

241 lines
11 KiB
TypeScript

import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";
import { buildApp } from "../src/app.js";
import { loadConfig } from "../src/config.js";
import { createDb } from "../src/db.js";
import { bearer, createTestApp, login, PASSWORD, resetDb, seedUser, type TestContext } from "./helpers.js";
let ctx: TestContext;
beforeAll(async () => {
ctx = await createTestApp();
});
afterAll(async () => {
await ctx.app.close();
await ctx.db.$disconnect();
});
beforeEach(() => resetDb(ctx.db));
describe("health", () => {
it("checks the database", async () => {
const res = await ctx.app.inject({ method: "GET", url: "/health" });
expect(res.json()).toEqual({ status: "ok", version: "dev" });
});
it("returns 503 degraded when the database is unreachable", async () => {
const config = loadConfig({
NODE_ENV: "test",
DATABASE_URL: "postgresql://[email protected]:1/photoreport_test",
JWT_SECRET: "test-secret-test-secret-test-secret-123",
});
const db = createDb(config.DATABASE_URL);
const app = await buildApp({ config, db });
try {
const res = await app.inject({ method: "GET", url: "/health" });
expect(res.statusCode).toBe(503);
expect(res.json()).toEqual({ status: "degraded", version: "dev" });
} finally {
await app.close();
await db.$disconnect();
}
});
});
describe("login", () => {
it("rejects wrong passwords and unknown users the same way", async () => {
await seedUser(ctx.db, "[email protected]");
const wrong = await ctx.app.inject({ method: "POST", url: "/v1/auth/login", payload: { email: "[email protected]", password: "nope" } });
const unknown = await ctx.app.inject({ method: "POST", url: "/v1/auth/login", payload: { email: "[email protected]", password: "nope" } });
expect(wrong.statusCode).toBe(401);
expect(unknown.statusCode).toBe(401);
expect(wrong.json().error).toBe(unknown.json().error);
});
it("normalises email case", async () => {
await seedUser(ctx.db, "[email protected]");
const res = await ctx.app.inject({ method: "POST", url: "/v1/auth/login", payload: { email: " [email protected] ", password: PASSWORD } });
expect(res.statusCode).toBe(200);
});
it("web login keeps the refresh token in an httpOnly cookie", async () => {
await seedUser(ctx.db, "[email protected]");
const res = await ctx.app.inject({ method: "POST", url: "/v1/auth/login", payload: { email: "[email protected]", password: PASSWORD } });
const cookie = res.cookies.find((c) => c.name === "pr_refresh");
expect(cookie?.httpOnly).toBe(true);
expect(cookie?.path).toBe("/v1/auth");
expect(res.json().refreshToken).toBeUndefined();
});
it("desktop login returns the refresh token in the body", async () => {
await seedUser(ctx.db, "[email protected]");
const { body, cookie } = await login(ctx.app, "[email protected]", "desktop");
expect(body.refreshToken).toBeTypeOf("string");
expect(cookie).toBeUndefined();
});
it("refuses disabled accounts", async () => {
const { user } = await seedUser(ctx.db, "[email protected]");
await ctx.db.user.update({ where: { id: user.id }, data: { disabledAt: new Date() } });
const res = await ctx.app.inject({ method: "POST", url: "/v1/auth/login", payload: { email: "[email protected]", password: PASSWORD } });
expect(res.statusCode).toBe(403);
});
});
describe("login rate limit", () => {
it("blocks repeated attempts for the same email and IP", async () => {
const strict = await createTestApp({ LOGIN_RATE_LIMIT_PER_MIN: "3" });
try {
const attempt = (email: string) =>
strict.app.inject({ method: "POST", url: "/v1/auth/login", payload: { email, password: "wrong" } });
for (let i = 0; i < 3; i++) expect((await attempt("[email protected]")).statusCode).toBe(401);
const blocked = await attempt("[email protected]");
expect(blocked.statusCode).toBe(429);
expect(blocked.json().error).toBe("rate_limited");
expect((await attempt("[email protected]")).statusCode).toBe(401); // other accounts unaffected
} finally {
await strict.app.close();
await strict.db.$disconnect();
}
});
});
describe("refresh rotation", () => {
it("rotates and detects reuse of an old token", async () => {
await seedUser(ctx.db, "[email protected]");
const first = await login(ctx.app, "[email protected]", "desktop");
const old = first.body.refreshToken;
const rotated = await ctx.app.inject({ method: "POST", url: "/v1/auth/refresh", payload: { refreshToken: old } });
expect(rotated.statusCode).toBe(200);
const fresh = rotated.json() as { accessToken: string; refreshToken: string };
expect(fresh.refreshToken).not.toBe(old);
const reuse = await ctx.app.inject({ method: "POST", url: "/v1/auth/refresh", payload: { refreshToken: old } });
expect(reuse.statusCode).toBe(401);
expect(reuse.json().error).toBe("refresh_token_reused");
// The whole family is revoked: the fresh pair stops working too.
const me = await ctx.app.inject({ method: "GET", url: "/v1/me", headers: bearer(fresh.accessToken) });
expect(me.statusCode).toBe(401);
const again = await ctx.app.inject({ method: "POST", url: "/v1/auth/refresh", payload: { refreshToken: fresh.refreshToken } });
expect(again.statusCode).toBe(401);
});
it("refreshes a web session from the cookie", async () => {
await seedUser(ctx.db, "[email protected]");
const { cookie } = await login(ctx.app, "[email protected]");
const res = await ctx.app.inject({ method: "POST", url: "/v1/auth/refresh", cookies: { pr_refresh: cookie ?? "" } });
expect(res.statusCode).toBe(200);
expect(res.cookies.find((c) => c.name === "pr_refresh")?.value).not.toBe(cookie);
});
});
describe("logout", () => {
it("revokes the session immediately", async () => {
await seedUser(ctx.db, "[email protected]");
const { body } = await login(ctx.app, "[email protected]", "desktop");
const out = await ctx.app.inject({ method: "POST", url: "/v1/auth/logout", payload: { refreshToken: body.refreshToken } });
expect(out.statusCode).toBe(204);
const me = await ctx.app.inject({ method: "GET", url: "/v1/me", headers: bearer(body.accessToken) });
expect(me.statusCode).toBe(401);
expect(me.json().error).toBe("session_revoked");
});
});
describe("desktop device sign-in", () => {
it("runs the whole flow: pending, approve, tokens, single use", async () => {
await seedUser(ctx.db, "[email protected]");
const web = await login(ctx.app, "[email protected]");
const start = await ctx.app.inject({ method: "POST", url: "/v1/auth/device", payload: { clientLabel: "MacBook Pro" } });
const grant = start.json() as { deviceCode: string; userCode: string; verificationUriComplete: string };
expect(grant.userCode).toMatch(/^[A-Z0-9]{4}-[A-Z0-9]{4}$/);
expect(grant.verificationUriComplete).toContain("https://app.test.photoreport.pt/device?code=");
const pending = await ctx.app.inject({ method: "POST", url: "/v1/auth/device/token", payload: { deviceCode: grant.deviceCode } });
expect(pending.json().error).toBe("authorization_pending");
const tooFast = await ctx.app.inject({ method: "POST", url: "/v1/auth/device/token", payload: { deviceCode: grant.deviceCode } });
expect(tooFast.json().error).toBe("slow_down");
const info = await ctx.app.inject({
method: "GET",
url: `/v1/auth/device/${grant.userCode.toLowerCase().replace("-", "")}`,
headers: bearer(web.body.accessToken),
});
expect(info.json().clientLabel).toBe("MacBook Pro");
const approve = await ctx.app.inject({
method: "POST",
url: "/v1/auth/device/approve",
headers: bearer(web.body.accessToken),
payload: { userCode: grant.userCode },
});
expect(approve.statusCode).toBe(200);
const tokens = await ctx.app.inject({ method: "POST", url: "/v1/auth/device/token", payload: { deviceCode: grant.deviceCode } });
expect(tokens.statusCode).toBe(200);
const desktop = tokens.json() as { accessToken: string; refreshToken: string };
expect(desktop.refreshToken).toBeTypeOf("string");
const me = await ctx.app.inject({ method: "GET", url: "/v1/me", headers: bearer(desktop.accessToken) });
expect(me.json().user.email).toBe("[email protected]");
const replay = await ctx.app.inject({ method: "POST", url: "/v1/auth/device/token", payload: { deviceCode: grant.deviceCode } });
expect(replay.json().error).toBe("invalid_grant");
});
it("reports denial", async () => {
await seedUser(ctx.db, "[email protected]");
const web = await login(ctx.app, "[email protected]");
const grant = (await ctx.app.inject({ method: "POST", url: "/v1/auth/device" })).json();
await ctx.app.inject({
method: "POST",
url: "/v1/auth/device/approve",
headers: bearer(web.body.accessToken),
payload: { userCode: grant.userCode, approve: false },
});
const res = await ctx.app.inject({ method: "POST", url: "/v1/auth/device/token", payload: { deviceCode: grant.deviceCode } });
expect(res.json().error).toBe("access_denied");
});
it("needs a signed-in user to approve", async () => {
const grant = (await ctx.app.inject({ method: "POST", url: "/v1/auth/device" })).json();
const res = await ctx.app.inject({ method: "POST", url: "/v1/auth/device/approve", payload: { userCode: grant.userCode } });
expect(res.statusCode).toBe(401);
});
});
describe("sign-up", () => {
it("is off by default (agency mode)", async () => {
const res = await ctx.app.inject({
method: "POST",
url: "/v1/auth/register",
payload: { email: "[email protected]", password: PASSWORD, name: "New" },
});
expect(res.statusCode).toBe(403);
});
it("creates an independent organization when enabled", async () => {
const open = await createTestApp({ ALLOW_SIGNUP: "true" });
try {
const res = await open.app.inject({
method: "POST",
url: "/v1/auth/register",
payload: { email: "[email protected]", password: PASSWORD, name: "João Fotógrafo" },
});
expect(res.statusCode).toBe(201);
const me = await open.app.inject({ method: "GET", url: "/v1/me", headers: bearer(res.json().accessToken) });
const membership = me.json().memberships[0];
expect(membership.role).toBe("OWNER");
expect(membership.organization.mode).toBe("INDEPENDENT");
expect(membership.organization.slug).toMatch(/^joao-fotografo-/);
const dup = await open.app.inject({
method: "POST",
url: "/v1/auth/register",
payload: { email: "[email protected]", password: PASSWORD, name: "Dup" },
});
expect(dup.statusCode).toBe(409);
} finally {
await open.app.close();
await open.db.$disconnect();
}
});
});