auth-login-route.test.ts 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  1. import { beforeEach, describe, expect, it, vi } from "vitest";
  2. import { NextRequest } from "next/server";
  3. const mockValidateKey = vi.hoisted(() => vi.fn());
  4. const mockSetAuthCookie = vi.hoisted(() => vi.fn());
  5. const mockGetSessionTokenMode = vi.hoisted(() => vi.fn());
  6. const mockGetLoginRedirectTarget = vi.hoisted(() => vi.fn());
  7. const mockGetTranslations = vi.hoisted(() => vi.fn());
  8. const mockLogger = vi.hoisted(() => ({
  9. warn: vi.fn(),
  10. error: vi.fn(),
  11. info: vi.fn(),
  12. debug: vi.fn(),
  13. }));
  14. vi.mock("@/lib/auth", () => ({
  15. validateKey: mockValidateKey,
  16. setAuthCookie: mockSetAuthCookie,
  17. getSessionTokenMode: mockGetSessionTokenMode,
  18. getLoginRedirectTarget: mockGetLoginRedirectTarget,
  19. toKeyFingerprint: vi.fn().mockResolvedValue("sha256:fake"),
  20. withNoStoreHeaders: <T>(res: T): T => {
  21. (res as any).headers.set("Cache-Control", "no-store, no-cache, must-revalidate");
  22. (res as any).headers.set("Pragma", "no-cache");
  23. return res;
  24. },
  25. }));
  26. vi.mock("next-intl/server", () => ({
  27. getTranslations: mockGetTranslations,
  28. }));
  29. vi.mock("@/lib/logger", () => ({
  30. logger: mockLogger,
  31. }));
  32. vi.mock("@/lib/config/env.schema", () => ({
  33. getEnvConfig: vi.fn().mockReturnValue({ ENABLE_SECURE_COOKIES: false }),
  34. }));
  35. vi.mock("@/lib/security/auth-response-headers", () => ({
  36. withAuthResponseHeaders: <T>(res: T): T => {
  37. (res as any).headers.set("Cache-Control", "no-store, no-cache, must-revalidate");
  38. (res as any).headers.set("Pragma", "no-cache");
  39. return res;
  40. },
  41. }));
  42. function makeRequest(
  43. body: unknown,
  44. opts?: { locale?: string; acceptLanguage?: string }
  45. ): NextRequest {
  46. const headers: Record<string, string> = { "Content-Type": "application/json" };
  47. if (opts?.acceptLanguage) {
  48. headers["accept-language"] = opts.acceptLanguage;
  49. }
  50. const req = new NextRequest("http://localhost/api/auth/login", {
  51. method: "POST",
  52. headers,
  53. body: JSON.stringify(body),
  54. });
  55. if (opts?.locale) {
  56. req.cookies.set("NEXT_LOCALE", opts.locale);
  57. }
  58. return req;
  59. }
  60. const fakeSession = {
  61. user: {
  62. id: 1,
  63. name: "Test User",
  64. description: "desc",
  65. role: "user" as const,
  66. },
  67. key: { canLoginWebUi: true },
  68. };
  69. const adminSession = {
  70. user: {
  71. id: -1,
  72. name: "Admin Token",
  73. description: "Environment admin session",
  74. role: "admin" as const,
  75. },
  76. key: { canLoginWebUi: true },
  77. };
  78. const readonlySession = {
  79. user: {
  80. id: 2,
  81. name: "Readonly User",
  82. description: "readonly",
  83. role: "user" as const,
  84. },
  85. key: { canLoginWebUi: false },
  86. };
  87. describe("POST /api/auth/login", () => {
  88. let POST: (request: NextRequest) => Promise<Response>;
  89. beforeEach(async () => {
  90. vi.resetModules();
  91. const mockT = vi.fn((key: string) => `translated:${key}`);
  92. mockGetTranslations.mockResolvedValue(mockT);
  93. mockSetAuthCookie.mockResolvedValue(undefined);
  94. mockGetSessionTokenMode.mockReturnValue("legacy");
  95. const mod = await import("@/app/api/auth/login/route");
  96. POST = mod.POST;
  97. });
  98. it("returns 400 when key is missing from body", async () => {
  99. const res = await POST(makeRequest({}));
  100. expect(res.status).toBe(400);
  101. const json = await res.json();
  102. expect(json).toEqual({ error: "translated:apiKeyRequired" });
  103. expect(mockValidateKey).not.toHaveBeenCalled();
  104. });
  105. it("returns 400 when key is empty string", async () => {
  106. const res = await POST(makeRequest({ key: "" }));
  107. expect(res.status).toBe(400);
  108. const json = await res.json();
  109. expect(json).toEqual({ error: "translated:apiKeyRequired" });
  110. });
  111. it("returns 401 when validateKey returns null", async () => {
  112. mockValidateKey.mockResolvedValue(null);
  113. const res = await POST(makeRequest({ key: "bad-key" }));
  114. expect(res.status).toBe(401);
  115. const json = await res.json();
  116. expect(json).toEqual({ error: "translated:apiKeyInvalidOrExpired" });
  117. expect(mockValidateKey).toHaveBeenCalledWith("bad-key", {
  118. allowReadOnlyAccess: true,
  119. });
  120. });
  121. it("returns 200 with correct body shape on valid key", async () => {
  122. mockValidateKey.mockResolvedValue(fakeSession);
  123. mockGetLoginRedirectTarget.mockReturnValue("/dashboard");
  124. const res = await POST(makeRequest({ key: "valid-key" }));
  125. expect(res.status).toBe(200);
  126. const json = await res.json();
  127. expect(json).toEqual({
  128. ok: true,
  129. user: {
  130. id: 1,
  131. name: "Test User",
  132. description: "desc",
  133. role: "user",
  134. },
  135. redirectTo: "/dashboard",
  136. loginType: "dashboard_user",
  137. });
  138. });
  139. it("calls setAuthCookie exactly once on success", async () => {
  140. mockValidateKey.mockResolvedValue(fakeSession);
  141. mockGetLoginRedirectTarget.mockReturnValue("/dashboard");
  142. await POST(makeRequest({ key: "valid-key" }));
  143. expect(mockSetAuthCookie).toHaveBeenCalledTimes(1);
  144. expect(mockSetAuthCookie).toHaveBeenCalledWith("valid-key");
  145. });
  146. it("returns redirectTo from getLoginRedirectTarget", async () => {
  147. mockValidateKey.mockResolvedValue(fakeSession);
  148. mockGetLoginRedirectTarget.mockReturnValue("/my-usage");
  149. const res = await POST(makeRequest({ key: "readonly-key" }));
  150. const json = await res.json();
  151. expect(json.redirectTo).toBe("/my-usage");
  152. expect(mockGetLoginRedirectTarget).toHaveBeenCalledWith(fakeSession);
  153. });
  154. it("returns loginType admin for admin session", async () => {
  155. mockValidateKey.mockResolvedValue(adminSession);
  156. mockGetLoginRedirectTarget.mockReturnValue("/dashboard");
  157. const res = await POST(makeRequest({ key: "admin-key" }));
  158. const json = await res.json();
  159. expect(json.loginType).toBe("admin");
  160. expect(json.redirectTo).toBe("/dashboard");
  161. });
  162. it("returns loginType dashboard_user for canLoginWebUi user session", async () => {
  163. mockValidateKey.mockResolvedValue(fakeSession);
  164. mockGetLoginRedirectTarget.mockReturnValue("/dashboard");
  165. const res = await POST(makeRequest({ key: "dashboard-key" }));
  166. const json = await res.json();
  167. expect(json.loginType).toBe("dashboard_user");
  168. expect(json.redirectTo).toBe("/dashboard");
  169. });
  170. it("returns loginType readonly_user for readonly session", async () => {
  171. mockValidateKey.mockResolvedValue(readonlySession);
  172. mockGetLoginRedirectTarget.mockReturnValue("/my-usage");
  173. const res = await POST(makeRequest({ key: "readonly-key" }));
  174. const json = await res.json();
  175. expect(json.loginType).toBe("readonly_user");
  176. expect(json.redirectTo).toBe("/my-usage");
  177. });
  178. it("returns 500 when validateKey throws", async () => {
  179. mockValidateKey.mockRejectedValue(new Error("DB connection failed"));
  180. const res = await POST(makeRequest({ key: "some-key" }));
  181. expect(res.status).toBe(500);
  182. const json = await res.json();
  183. expect(json).toEqual({ error: "translated:serverError" });
  184. expect(mockLogger.error).toHaveBeenCalled();
  185. });
  186. it("returns 500 when request.json() throws (malformed body)", async () => {
  187. const req = new NextRequest("http://localhost/api/auth/login", {
  188. method: "POST",
  189. headers: { "Content-Type": "application/json" },
  190. body: "not-valid-json{{{",
  191. });
  192. const res = await POST(req);
  193. expect(res.status).toBe(500);
  194. const json = await res.json();
  195. expect(json).toEqual({ error: "translated:serverError" });
  196. });
  197. it("uses NEXT_LOCALE cookie for translations", async () => {
  198. mockValidateKey.mockResolvedValue(null);
  199. await POST(makeRequest({ key: "x" }, { locale: "ja" }));
  200. expect(mockGetTranslations).toHaveBeenCalledWith({
  201. locale: "ja",
  202. namespace: "auth.errors",
  203. });
  204. });
  205. it("detects locale from accept-language header", async () => {
  206. mockValidateKey.mockResolvedValue(null);
  207. await POST(makeRequest({ key: "x" }, { acceptLanguage: "ru;q=1.0" }));
  208. expect(mockGetTranslations).toHaveBeenCalledWith({
  209. locale: "ru",
  210. namespace: "auth.errors",
  211. });
  212. });
  213. it("falls back to defaultLocale when getTranslations fails for requested locale", async () => {
  214. const mockT = vi.fn((key: string) => `fallback:${key}`);
  215. mockGetTranslations
  216. .mockRejectedValueOnce(new Error("locale not found"))
  217. .mockResolvedValueOnce(mockT);
  218. mockValidateKey.mockResolvedValue(null);
  219. const res = await POST(makeRequest({ key: "x" }, { locale: "ja" }));
  220. expect(mockGetTranslations).toHaveBeenCalledTimes(2);
  221. expect(mockGetTranslations).toHaveBeenNthCalledWith(1, {
  222. locale: "ja",
  223. namespace: "auth.errors",
  224. });
  225. expect(mockGetTranslations).toHaveBeenNthCalledWith(2, {
  226. locale: "zh-CN",
  227. namespace: "auth.errors",
  228. });
  229. const json = await res.json();
  230. expect(json.error).toBe("fallback:apiKeyInvalidOrExpired");
  231. });
  232. it("returns null translation when both locale and fallback fail", async () => {
  233. mockGetTranslations
  234. .mockRejectedValueOnce(new Error("fail"))
  235. .mockRejectedValueOnce(new Error("fallback fail"));
  236. mockValidateKey.mockResolvedValue(null);
  237. const res = await POST(makeRequest({ key: "x" }));
  238. expect(res.status).toBe(401);
  239. const json = await res.json();
  240. expect(json).toEqual({ error: "Authentication failed" });
  241. expect(mockLogger.warn).toHaveBeenCalled();
  242. expect(mockLogger.error).toHaveBeenCalled();
  243. });
  244. it("falls back to defaultLocale when no locale cookie or accept-language", async () => {
  245. mockValidateKey.mockResolvedValue(null);
  246. await POST(makeRequest({ key: "x" }));
  247. expect(mockGetTranslations).toHaveBeenCalledWith({
  248. locale: "zh-CN",
  249. namespace: "auth.errors",
  250. });
  251. });
  252. });