|
| 1 | +import { Readable } from "node:stream"; |
| 2 | +import Fastify, { type FastifyInstance } from "fastify"; |
| 3 | +import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest"; |
| 4 | +import { mockAdminSession } from "./admin-test-helpers.js"; |
| 5 | + |
| 6 | +// Auth guard mock — all three exports required. |
| 7 | +const fakeSession = mockAdminSession(); |
| 8 | +const mockRequireAdmin = vi.fn().mockResolvedValue(fakeSession); |
| 9 | +const mockGetAdminSession = vi.fn().mockReturnValue(fakeSession); |
| 10 | +const mockTryAdminSession = vi.fn().mockResolvedValue(fakeSession); |
| 11 | + |
| 12 | +vi.mock("../../utils/require-admin.js", () => ({ |
| 13 | + requireAdmin: (...args: unknown[]) => mockRequireAdmin(...args), |
| 14 | + getAdminSession: (...args: unknown[]) => mockGetAdminSession(...args), |
| 15 | + tryAdminSession: (...args: unknown[]) => mockTryAdminSession(...args), |
| 16 | +})); |
| 17 | + |
| 18 | +// Audit log. |
| 19 | +const mockWriteAuditLog = vi.fn().mockResolvedValue(undefined); |
| 20 | +vi.mock("../../utils/audit-log.js", () => ({ |
| 21 | + writeAuditLog: (...args: unknown[]) => mockWriteAuditLog(...args), |
| 22 | +})); |
| 23 | + |
| 24 | +// Fake Redis. `scanStream` returns a stream emitting one array of the keys |
| 25 | +// whose name matches the requested glob prefix. `flushdb` is a spy so the |
| 26 | +// "never wipes the whole DB" guarantee is assertable. |
| 27 | +const cacheStore = new Map<string, string>([ |
| 28 | + ["int:geocoding:a", "1"], |
| 29 | + ["int:geocoding:b", "1"], |
| 30 | + ["int:routing:c", "1"], |
| 31 | + ["cache:geocode:d", "1"], |
| 32 | + ["session:user:1", "1"], // NOT app-owned — must never be touched. |
| 33 | +]); |
| 34 | + |
| 35 | +function prefixFromGlob(match: string): string { |
| 36 | + return match.endsWith("*") ? match.slice(0, -1) : match; |
| 37 | +} |
| 38 | + |
| 39 | +const mockScanStream = vi.fn((opts: { match: string }) => { |
| 40 | + const prefix = prefixFromGlob(opts.match); |
| 41 | + const keys = [...cacheStore.keys()].filter((k) => k.startsWith(prefix)); |
| 42 | + return Readable.from([keys]); |
| 43 | +}); |
| 44 | + |
| 45 | +const mockUnlink = vi.fn((...keys: string[]) => { |
| 46 | + let removed = 0; |
| 47 | + for (const k of keys) { |
| 48 | + if (cacheStore.delete(k)) removed += 1; |
| 49 | + } |
| 50 | + return Promise.resolve(removed); |
| 51 | +}); |
| 52 | + |
| 53 | +const mockFlushdb = vi.fn(() => Promise.resolve("OK")); |
| 54 | + |
| 55 | +const fakeRedis = { |
| 56 | + scanStream: mockScanStream, |
| 57 | + unlink: mockUnlink, |
| 58 | + flushdb: mockFlushdb, |
| 59 | +}; |
| 60 | + |
| 61 | +vi.mock("../../redis.js", () => ({ redis: fakeRedis })); |
| 62 | + |
| 63 | +let app: FastifyInstance; |
| 64 | + |
| 65 | +beforeAll(async () => { |
| 66 | + const { adminCacheRoute } = await import("../admin-cache.js"); |
| 67 | + app = Fastify({ logger: false }); |
| 68 | + await app.register(adminCacheRoute); |
| 69 | + await app.ready(); |
| 70 | +}); |
| 71 | + |
| 72 | +afterAll(() => app.close()); |
| 73 | +afterEach(() => { |
| 74 | + vi.clearAllMocks(); |
| 75 | + // Restore the store between tests so destructive tests don't leak. |
| 76 | + cacheStore.clear(); |
| 77 | + cacheStore.set("int:geocoding:a", "1"); |
| 78 | + cacheStore.set("int:geocoding:b", "1"); |
| 79 | + cacheStore.set("int:routing:c", "1"); |
| 80 | + cacheStore.set("cache:geocode:d", "1"); |
| 81 | + cacheStore.set("session:user:1", "1"); |
| 82 | +}); |
| 83 | + |
| 84 | +describe("GET /admin/cache", () => { |
| 85 | + it("lists app-owned namespaces with key counts", async () => { |
| 86 | + const res = await app.inject({ method: "GET", url: "/admin/cache" }); |
| 87 | + |
| 88 | + expect(res.statusCode).toBe(200); |
| 89 | + const body = res.json() as { namespaces: Array<{ namespace: string; keyCount: number }> }; |
| 90 | + expect(Array.isArray(body.namespaces)).toBe(true); |
| 91 | + |
| 92 | + const byName = Object.fromEntries(body.namespaces.map((n) => [n.namespace, n.keyCount])); |
| 93 | + expect(byName["int:geocoding"]).toBe(2); |
| 94 | + expect(byName["int:routing"]).toBe(1); |
| 95 | + expect(byName["cache:geocode"]).toBe(1); |
| 96 | + // The non-app-owned `session:*` prefix is never scanned. |
| 97 | + expect(byName["session:user"]).toBeUndefined(); |
| 98 | + }); |
| 99 | + |
| 100 | + it("rejects unauthenticated requests with 401", async () => { |
| 101 | + mockRequireAdmin.mockRejectedValueOnce( |
| 102 | + Object.assign(new Error("Authentication required"), { statusCode: 401 }), |
| 103 | + ); |
| 104 | + const res = await app.inject({ method: "GET", url: "/admin/cache" }); |
| 105 | + expect(res.statusCode).toBe(401); |
| 106 | + }); |
| 107 | +}); |
| 108 | + |
| 109 | +describe("POST /admin/cache/clear", () => { |
| 110 | + it("clears a single namespace and audit-logs it", async () => { |
| 111 | + const res = await app.inject({ |
| 112 | + method: "POST", |
| 113 | + url: "/admin/cache/clear", |
| 114 | + payload: { namespace: "geocoding" }, |
| 115 | + }); |
| 116 | + |
| 117 | + expect(res.statusCode).toBe(200); |
| 118 | + expect(res.json()).toEqual({ deleted: 2 }); |
| 119 | + // Only the matching prefix was removed; other keys remain. |
| 120 | + expect(cacheStore.has("int:routing:c")).toBe(true); |
| 121 | + expect(cacheStore.has("cache:geocode:d")).toBe(true); |
| 122 | + expect(cacheStore.has("session:user:1")).toBe(true); |
| 123 | + expect(mockWriteAuditLog).toHaveBeenCalledWith( |
| 124 | + expect.objectContaining({ |
| 125 | + action: "cache.clear", |
| 126 | + targetType: "cache", |
| 127 | + details: { namespace: "geocoding" }, |
| 128 | + }), |
| 129 | + ); |
| 130 | + expect(mockFlushdb).not.toHaveBeenCalled(); |
| 131 | + }); |
| 132 | + |
| 133 | + it("clears all app-owned prefixes but never the rest of the DB", async () => { |
| 134 | + const res = await app.inject({ method: "POST", url: "/admin/cache/clear", payload: {} }); |
| 135 | + |
| 136 | + expect(res.statusCode).toBe(200); |
| 137 | + // int:* (3) + cache:* (1) removed; session:* untouched. |
| 138 | + expect(res.json()).toEqual({ deleted: 4 }); |
| 139 | + expect(cacheStore.has("session:user:1")).toBe(true); |
| 140 | + expect(mockFlushdb).not.toHaveBeenCalled(); |
| 141 | + }); |
| 142 | + |
| 143 | + it('treats namespace "all" the same as an omitted namespace', async () => { |
| 144 | + const res = await app.inject({ |
| 145 | + method: "POST", |
| 146 | + url: "/admin/cache/clear", |
| 147 | + payload: { namespace: "all" }, |
| 148 | + }); |
| 149 | + |
| 150 | + expect(res.statusCode).toBe(200); |
| 151 | + expect(res.json()).toEqual({ deleted: 4 }); |
| 152 | + expect(mockFlushdb).not.toHaveBeenCalled(); |
| 153 | + }); |
| 154 | + |
| 155 | + it("rejects a namespace that resolves outside the app prefixes with 400", async () => { |
| 156 | + const res = await app.inject({ |
| 157 | + method: "POST", |
| 158 | + url: "/admin/cache/clear", |
| 159 | + payload: { namespace: "*" }, |
| 160 | + }); |
| 161 | + |
| 162 | + expect(res.statusCode).toBe(400); |
| 163 | + expect(mockUnlink).not.toHaveBeenCalled(); |
| 164 | + expect(mockFlushdb).not.toHaveBeenCalled(); |
| 165 | + }); |
| 166 | + |
| 167 | + it("rejects unauthenticated requests with 401", async () => { |
| 168 | + mockRequireAdmin.mockRejectedValueOnce( |
| 169 | + Object.assign(new Error("Authentication required"), { statusCode: 401 }), |
| 170 | + ); |
| 171 | + const res = await app.inject({ method: "POST", url: "/admin/cache/clear", payload: {} }); |
| 172 | + expect(res.statusCode).toBe(401); |
| 173 | + }); |
| 174 | +}); |
| 175 | + |
| 176 | +describe("when Redis is disabled", () => { |
| 177 | + it("GET returns an empty list and POST reports zero deletions", async () => { |
| 178 | + vi.resetModules(); |
| 179 | + vi.doMock("../../redis.js", () => ({ redis: null })); |
| 180 | + vi.doMock("../../utils/require-admin.js", () => ({ |
| 181 | + requireAdmin: (...args: unknown[]) => mockRequireAdmin(...args), |
| 182 | + getAdminSession: (...args: unknown[]) => mockGetAdminSession(...args), |
| 183 | + tryAdminSession: (...args: unknown[]) => mockTryAdminSession(...args), |
| 184 | + })); |
| 185 | + vi.doMock("../../utils/audit-log.js", () => ({ |
| 186 | + writeAuditLog: (...args: unknown[]) => mockWriteAuditLog(...args), |
| 187 | + })); |
| 188 | + |
| 189 | + const { adminCacheRoute } = await import("../admin-cache.js"); |
| 190 | + const nullApp = Fastify({ logger: false }); |
| 191 | + await nullApp.register(adminCacheRoute); |
| 192 | + await nullApp.ready(); |
| 193 | + |
| 194 | + const listRes = await nullApp.inject({ method: "GET", url: "/admin/cache" }); |
| 195 | + expect(listRes.json()).toEqual({ namespaces: [] }); |
| 196 | + |
| 197 | + const clearRes = await nullApp.inject({ |
| 198 | + method: "POST", |
| 199 | + url: "/admin/cache/clear", |
| 200 | + payload: {}, |
| 201 | + }); |
| 202 | + expect(clearRes.json()).toEqual({ deleted: 0 }); |
| 203 | + |
| 204 | + await nullApp.close(); |
| 205 | + vi.doUnmock("../../redis.js"); |
| 206 | + vi.resetModules(); |
| 207 | + }); |
| 208 | +}); |
0 commit comments