fix(BUG-106): DB fallback for downgradeByCustomer and recover route
All checks were successful
Build & Deploy to Staging / Build & Deploy to Staging (push) Successful in 13m7s
All checks were successful
Build & Deploy to Staging / Build & Deploy to Staging (push) Successful in 13m7s
- downgradeByCustomer now queries DB when key not in memory cache, preventing cancelled customers from keeping Pro access in multi-pod setups - recover/verify endpoint falls back to DB lookup when cache miss on email - Added TDD tests for both fallback paths (4 new tests)
This commit is contained in:
parent
4473641ee1
commit
b964b98a8b
4 changed files with 240 additions and 2 deletions
75
src/__tests__/keys-downgrade.test.ts
Normal file
75
src/__tests__/keys-downgrade.test.ts
Normal file
|
|
@ -0,0 +1,75 @@
|
|||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
// Override the global setup.ts mock for keys — we need the REAL implementation
|
||||
vi.unmock("../services/keys.js");
|
||||
|
||||
// Keep db mocked (setup.ts already does this, but be explicit about our mock)
|
||||
vi.mock("../services/db.js", () => ({
|
||||
default: { query: vi.fn(), connect: vi.fn(), on: vi.fn(), end: vi.fn() },
|
||||
pool: { query: vi.fn(), connect: vi.fn(), on: vi.fn(), end: vi.fn() },
|
||||
queryWithRetry: vi.fn().mockResolvedValue({ rows: [], rowCount: 0 }),
|
||||
connectWithRetry: vi.fn().mockResolvedValue(undefined),
|
||||
initDatabase: vi.fn().mockResolvedValue(undefined),
|
||||
cleanupStaleData: vi.fn(),
|
||||
isTransientError: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("../services/logger.js", () => ({
|
||||
default: { info: vi.fn(), error: vi.fn(), warn: vi.fn(), debug: vi.fn() },
|
||||
}));
|
||||
|
||||
import { queryWithRetry } from "../services/db.js";
|
||||
import { downgradeByCustomer } from "../services/keys.js";
|
||||
|
||||
const mockQuery = vi.mocked(queryWithRetry);
|
||||
|
||||
describe("downgradeByCustomer DB fallback (BUG-106)", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it("returns true and updates DB when key is NOT in cache but IS in DB", async () => {
|
||||
mockQuery
|
||||
.mockResolvedValueOnce({
|
||||
rows: [
|
||||
{
|
||||
key: "df_pro_abc123",
|
||||
tier: "pro",
|
||||
email: "user@example.com",
|
||||
created_at: "2026-01-01T00:00:00.000Z",
|
||||
stripe_customer_id: "cus_123",
|
||||
},
|
||||
],
|
||||
rowCount: 1,
|
||||
} as any)
|
||||
.mockResolvedValueOnce({ rows: [], rowCount: 1 } as any); // UPDATE
|
||||
|
||||
const result = await downgradeByCustomer("cus_123");
|
||||
|
||||
expect(result).toBe(true);
|
||||
expect(mockQuery).toHaveBeenCalledWith(
|
||||
expect.stringContaining("SELECT"),
|
||||
expect.arrayContaining(["cus_123"])
|
||||
);
|
||||
expect(mockQuery).toHaveBeenCalledWith(
|
||||
expect.stringContaining("UPDATE"),
|
||||
expect.arrayContaining(["cus_123"])
|
||||
);
|
||||
});
|
||||
|
||||
it("returns false when key is NOT in cache AND NOT in DB", async () => {
|
||||
mockQuery.mockResolvedValueOnce({ rows: [], rowCount: 0 } as any);
|
||||
|
||||
const result = await downgradeByCustomer("cus_nonexistent");
|
||||
|
||||
expect(result).toBe(false);
|
||||
expect(mockQuery).toHaveBeenCalledWith(
|
||||
expect.stringContaining("SELECT"),
|
||||
expect.arrayContaining(["cus_nonexistent"])
|
||||
);
|
||||
const updateCalls = mockQuery.mock.calls.filter((c) =>
|
||||
(c[0] as string).includes("UPDATE")
|
||||
);
|
||||
expect(updateCalls).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
117
src/__tests__/recover-db-fallback.test.ts
Normal file
117
src/__tests__/recover-db-fallback.test.ts
Normal file
|
|
@ -0,0 +1,117 @@
|
|||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
// Unmock keys to use real getAllKeys (but we'll mock it ourselves)
|
||||
vi.unmock("../services/keys.js");
|
||||
vi.unmock("../services/verification.js");
|
||||
vi.unmock("../services/email.js");
|
||||
|
||||
vi.mock("../services/db.js", () => ({
|
||||
default: { query: vi.fn(), connect: vi.fn(), on: vi.fn(), end: vi.fn() },
|
||||
pool: { query: vi.fn(), connect: vi.fn(), on: vi.fn(), end: vi.fn() },
|
||||
queryWithRetry: vi.fn().mockResolvedValue({ rows: [], rowCount: 0 }),
|
||||
connectWithRetry: vi.fn().mockResolvedValue(undefined),
|
||||
initDatabase: vi.fn().mockResolvedValue(undefined),
|
||||
cleanupStaleData: vi.fn(),
|
||||
isTransientError: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("../services/logger.js", () => ({
|
||||
default: { info: vi.fn(), error: vi.fn(), warn: vi.fn(), debug: vi.fn() },
|
||||
}));
|
||||
|
||||
vi.mock("../services/verification.js", () => ({
|
||||
createPendingVerification: vi.fn(),
|
||||
verifyCode: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("../services/email.js", () => ({
|
||||
sendVerificationEmail: vi.fn().mockResolvedValue(undefined),
|
||||
}));
|
||||
|
||||
vi.mock("../services/keys.js", () => ({
|
||||
getAllKeys: vi.fn().mockReturnValue([]),
|
||||
loadKeys: vi.fn().mockResolvedValue(undefined),
|
||||
isValidKey: vi.fn(),
|
||||
getKeyInfo: vi.fn(),
|
||||
isProKey: vi.fn(),
|
||||
createFreeKey: vi.fn(),
|
||||
createProKey: vi.fn(),
|
||||
downgradeByCustomer: vi.fn(),
|
||||
findKeyByCustomerId: vi.fn(),
|
||||
updateKeyEmail: vi.fn(),
|
||||
updateEmailByCustomer: vi.fn(),
|
||||
}));
|
||||
|
||||
import { queryWithRetry } from "../services/db.js";
|
||||
import { getAllKeys } from "../services/keys.js";
|
||||
import { verifyCode } from "../services/verification.js";
|
||||
import express from "express";
|
||||
import request from "supertest";
|
||||
import { recoverRouter } from "../routes/recover.js";
|
||||
|
||||
const mockQuery = vi.mocked(queryWithRetry);
|
||||
const mockGetAllKeys = vi.mocked(getAllKeys);
|
||||
const mockVerifyCode = vi.mocked(verifyCode);
|
||||
|
||||
function createApp() {
|
||||
const app = express();
|
||||
app.use(express.json());
|
||||
app.use("/v1/recover", recoverRouter);
|
||||
return app;
|
||||
}
|
||||
|
||||
describe("recover verify DB fallback", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it("falls back to DB when cache has no matching email after verify succeeds", async () => {
|
||||
mockVerifyCode.mockResolvedValueOnce({ status: "ok" } as any);
|
||||
mockGetAllKeys.mockReturnValueOnce([]); // cache empty
|
||||
|
||||
// DB fallback returns the key
|
||||
mockQuery.mockResolvedValueOnce({
|
||||
rows: [
|
||||
{
|
||||
key: "df_pro_xyz",
|
||||
tier: "pro",
|
||||
email: "user@test.com",
|
||||
created_at: "2026-01-01T00:00:00.000Z",
|
||||
stripe_customer_id: null,
|
||||
},
|
||||
],
|
||||
rowCount: 1,
|
||||
} as any);
|
||||
|
||||
const app = createApp();
|
||||
const res = await request(app)
|
||||
.post("/v1/recover/verify")
|
||||
.send({ email: "user@test.com", code: "123456" });
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.status).toBe("recovered");
|
||||
expect(res.body.apiKey).toBe("df_pro_xyz");
|
||||
expect(res.body.tier).toBe("pro");
|
||||
|
||||
expect(mockQuery).toHaveBeenCalledWith(
|
||||
expect.stringContaining("SELECT"),
|
||||
expect.arrayContaining(["user@test.com"])
|
||||
);
|
||||
});
|
||||
|
||||
it("returns 'no key found' when not in cache AND not in DB", async () => {
|
||||
mockVerifyCode.mockResolvedValueOnce({ status: "ok" } as any);
|
||||
mockGetAllKeys.mockReturnValueOnce([]);
|
||||
mockQuery.mockResolvedValueOnce({ rows: [], rowCount: 0 } as any);
|
||||
|
||||
const app = createApp();
|
||||
const res = await request(app)
|
||||
.post("/v1/recover/verify")
|
||||
.send({ email: "nobody@test.com", code: "123456" });
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.status).toBe("recovered");
|
||||
expect(res.body.apiKey).toBeUndefined();
|
||||
expect(res.body.message).toContain("No API key found");
|
||||
});
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue